如何在脚本中使用sudo执行多个命令[重复]

时间:2021-10-09 05:27:26

This question already has an answer here:

这个问题在这里已有答案:

Can we use heredocs to run multiple commands using sudo?

我们可以使用heredocs使用sudo运行多个命令吗?

I am facing an issue (need to pass password for every command) while running multiple commands:

我在运行多个命令时遇到问题(需要为每个命令传递密码):

echo 'password'| sudo -S ls
echo 'password'| sudo -S cat /var/log/abc.log

Can anyone help me how to automate this in a script? Like:

任何人都可以帮我如何在脚本中自动化这个?喜欢:

echo 'password' | sudo -S << ENDBLOCK
ls
cat
ENDBLOCK

3 个解决方案

#1


4  

you can run sh -c ..., but remember to quote properly.

你可以运行sh -c ...,但记得正确引用。

sudo sh -c 'id; echo another command ; id'

sudo must see this as a single argument for the sh command.

sudo必须将此视为sh命令的单个参数。

Of course you can use new line instead of semicolon:

当然你可以使用换行而不是分号:

sudo sh -c '
  echo "I am root"
  id
  echo "another command"
  id
'

#2


2  

One way is to write a script with all the things you need to do with sudo and then run the script with sudo.

一种方法是编写一个脚本,其中包含使用sudo所需的所有内容,然后使用sudo运行脚本。

#3


1  

you could put all your commands in a script. Then

你可以将所有命令放在脚本中。然后

  • sudo ./script.sh
  • put permissions for script.sh in /etc/sudoers.d; that way you'll never need to type your password again (for that script)
  • 在/etc/sudoers.d中添加script.sh的权限;那样你再也不需要输入密码了(对于那个脚本)

#1


4  

you can run sh -c ..., but remember to quote properly.

你可以运行sh -c ...,但记得正确引用。

sudo sh -c 'id; echo another command ; id'

sudo must see this as a single argument for the sh command.

sudo必须将此视为sh命令的单个参数。

Of course you can use new line instead of semicolon:

当然你可以使用换行而不是分号:

sudo sh -c '
  echo "I am root"
  id
  echo "another command"
  id
'

#2


2  

One way is to write a script with all the things you need to do with sudo and then run the script with sudo.

一种方法是编写一个脚本,其中包含使用sudo所需的所有内容,然后使用sudo运行脚本。

#3


1  

you could put all your commands in a script. Then

你可以将所有命令放在脚本中。然后

  • sudo ./script.sh
  • put permissions for script.sh in /etc/sudoers.d; that way you'll never need to type your password again (for that script)
  • 在/etc/sudoers.d中添加script.sh的权限;那样你再也不需要输入密码了(对于那个脚本)