Linux 使用 sudo 密码作为参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11955298/
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-08-06 14:04:50  来源:igfitidea点击:

Use sudo with password as parameter

linuxbashsudo

提问by ccman

I would like to run sudo with my password as parameter so that I can use it for a script. I tried

我想用我的密码作为参数运行 sudo 以便我可以将它用于脚本。我试过

sudo -S mypassword execute_command

but without any success. Any suggestions?

但没有任何成功。有什么建议?

回答by matteomattei

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

回答by stonesam92

The -S switch makes sudo read the password from STDIN. This means you can do

-S 开关使 sudo 从 STDIN 读取密码。这意味着你可以做到

echo mypassword | sudo -S command

to pass the password to sudo

将密码传递给 sudo

However, the suggestions by others that do not involve passing the password as part of a command such as checking if the user is root are probably much better ideas for security reasons

但是,出于安全原因,不涉及将密码作为命令的一部分传递的其他人的建议(例如检查用户是否为 root)可能是更好的主意

回答by perreal

You can set the sbit for your script so that it does not need sudoand runs as root (and you do not need to write your root password in the script):

您可以s为您的脚本设置位,以便它不需要sudo并以 root 身份运行(并且您不需要在脚本中写入您的 root 密码):

sudo chmod +s myscript

回答by Lucas Holt

One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.

一种选择是使用 -A 标志来执行 sudo。这会运行一个程序来询问密码。与其询问,您还可以使用一个脚本来输出密码,以便程序继续运行。

回答by kbdjockey

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi