使用带密码的 sudo 作为参数

我想用我的密码作为参数运行 sudo,这样我就可以将它用于脚本。我尽力了

sudo -S mypassword execute_command

但是没有成功,有什么建议吗?

184979 次浏览
echo -e "YOURPASSWORD\n" | sudo -S yourcommand

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

echo mypassword | sudo -S command

to pass the password to 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

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

sudo chmod +s myscript

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.

# 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