Automatically input a password when a bash script

2019-03-16 09:23发布

问题:

This question already has an answer here:

  • How to provide password to a command that prompts for one in bash? 7 answers

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)?

回答1:

Spawning an expect session within your bash script is typically how you automate interactive prompts.

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 huge security hole to store your root password in a bash script.

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