运行 bash 脚本时自动输入密码 [英] Automatically input a password when a bash script is run
问题描述
例如,假设我有一个脚本说:
For example, say if I have a script saying:
#!/bin/bash
sudo setpci -s 00:02.0 F4.B=00
如何将 root 密码放入脚本中,以便它在读取和执行 sudo 行时接受它作为密码(这样我就不必手动输入)?
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)?
推荐答案
在你的 bash 脚本中生成一个 expect 会话是通常是如何自动化交互式提示.
Spawning an expect session within your bash script is typically how you automate interactive prompts.
例如
expect -c "
spawn sudo setpci -s 00:02.0 F4.B=00
expect -nocase "password:" {send "$PASS
"; interact}
"
请注意,在这种情况下,这不是推荐的方法,因为将 root 密码存储在 bash 脚本中是一个巨大安全漏洞.
Note that this isn't the recommended approach in this case as it is a huge security hole to store your root password in a bash script.
正确的解决方案是编辑您的 /etc/sudoers/
以不提示您输入该二进制文件的密码.
The correct solution would be to edit your /etc/sudoers/
to not prompt you for a password for that binary.
#in /etc/sudoers
neohexane ALL=(ALL) NOPASSWD : /usr/bin/setpci
这篇关于运行 bash 脚本时自动输入密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!