Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically input a password when a bash script is run [duplicate]

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

like image 243
Aaron Hooper Avatar asked May 15 '12 18:05

Aaron Hooper


1 Answers

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
like image 84
cmh Avatar answered Oct 29 '22 00:10

cmh