运行 bash 脚本时自动输入密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10606958/
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
Automatically input a password when a bash script is run
提问by Aaron Hooper
For example, say if I have a script saying:
例如,假设我有一个脚本说:
#!/bin/bash
sudo setpci -s 00:02.0 F4.B=00
How do I put the root password into the script so that it accepts it as the password when it reads and executes the sudo line (so I don't have to type it manually)?
我如何将 root 密码放入脚本中,以便它在读取和执行 sudo 行时接受它作为密码(所以我不必手动输入它)?
回答by cmh
Spawning an expectsession within your bash script is typically how you automate interactive prompts.
在您的 bash 脚本中生成一个期望会话通常是您自动化交互式提示的方式。
e.g.
例如
expect -c "
spawn sudo setpci -s 00:02.0 F4.B=00
expect -nocase \"password:\" {send \"$PASS\r\"; interact}
"
Note that this isn't the recommended approach in this case as it is a hugesecurity hole to store your root password in a bash script.
请注意,在这种情况下,这不是推荐的方法,因为将 root 密码存储在 bash 脚本中是一个巨大的安全漏洞。
The correct solution would be to edit your /etc/sudoers/
to not prompt you for a password for that binary.
正确的解决方案是编辑您的/etc/sudoers/
,不提示您输入该二进制文件的密码。
#in /etc/sudoers
neohexane ALL=(ALL) NOPASSWD : /usr/bin/setpci