6

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

Aaron Hooper
  • 798
  • 2
  • 6
  • 14

1 Answers1

27

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
cmh
  • 10,612
  • 5
  • 30
  • 40
  • 1
    Is there any reason you can't use the `/etc/sudoers/` approach. That would be my reccomendation. – cmh May 15 '12 at 19:00
  • 3
    "isn't recommended" seems like an understatement. I'd remove the expect solution altogether. Unless this is his own personal box, he should absolutely not be leaving the root password lying around in a plain text file. – chepner May 15 '12 at 19:22
  • 3
    I think it's worth keeping as an example of how to use expect. I'll emphasise how not recommended it is. – cmh May 15 '12 at 19:25
  • @cmh : Will this work for linux ..If no, then please give me a solution – Nevin Raj Victor Mar 26 '15 at 05:29
  • Leaving the password "Lying around" is the real problem with security. You can not automate a system unless the automatic has the password, and giving that password securely is a major pain. Even using the best method given... (using "--login-path"), is technically not real secure as the password is still there, just encrypted. Without more information what is to say a hacker that gets on the system can extract the password from the ".mylogin.cnf" file? Still it that is the most secure method so far. – anthony Sep 02 '16 at 06:41