5

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

0

1 Answer 1

28

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
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any reason you can't use the /etc/sudoers/ approach. That would be my reccomendation.
"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.
I think it's worth keeping as an example of how to use expect. I'll emphasise how not recommended it is.
@cmh : Will this work for linux ..If no, then please give me a solution
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.