bash 如何在脚本中使用 sudo 执行多个命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30341867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:00:25  来源:igfitidea点击:

How to execute multiple commands with sudo in script

linuxbashshellubuntu-12.04sudoers

提问by Sasikiran Vaddi

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

回答by Micha? ?rajer

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

您可以运行sh -c ...,但请记住正确引用。

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

sudomust see this as a single argument for the shcommand.

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

Of course you can use new line instead of semicolon:

当然,您可以使用换行符代替分号:

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

回答by thinker

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 运行该脚本。

回答by Chris Maes

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)
  • 须藤 ./script.sh
  • 将 script.sh 的权限放在 /etc/sudoers.d 中;这样你就永远不需要再次输入密码(对于那个脚本)