如何在 RedHat 上的 bash 脚本中无需输入密码即可切换到 root 用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10882310/
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
how to switch to root user without entering password in bash script on RedHat
提问by Ibrahim
I want to switch to root user in bash script on RedHat by specifying the password in code rather than entering it.
我想通过在代码中指定密码而不是输入密码,在 RedHat 上的 bash 脚本中切换到 root 用户。
Any help will be highly appreciated.
任何帮助将不胜感激。
Thanks
谢谢
回答by Paused until further notice.
It's not a good idea to store passwords in plain text in a script. You can use visudoto edit the sudoersfile and allow users to run a command using sudowithout using a password.
在脚本中以纯文本形式存储密码不是一个好主意。您可以使用visudo编辑sudoers文件并允许用户在sudo不使用密码的情况下运行命令。
回答by sehe
The flexibility of sudo is widely under-estimated. This leads to very poor practices (like the sudo su -canon-ball surgery method).
sudo 的灵活性被广泛低估。这会导致非常糟糕的做法(如sudo su -炮弹手术方法)。
A much better method is to specificly allow the commands you intend to allow without use of a password:
更好的方法是在不使用密码的情况下专门允许您打算允许的命令:
phill = NOPASSWD: /bin/ls, /usr/bin/lprm
See for more examples: Shell script - Sudo-permissions lost over time
回答by Jeffrey Vandenborne
Let sudo read from stdin using the -S flag
让 sudo 使用 -S 标志从标准输入读取
sudo -S mkdir /mnt/somedir <<END
password here
END
This will let a user create a directory in /mnt owned by root
这将让用户在 root 拥有的 /mnt 中创建一个目录
EDIT: this doesn't seem to work for the "su" command, yet I think this solution might be helpful
编辑:这似乎不适用于“su”命令,但我认为此解决方案可能会有所帮助

