user2460869
user2460869

Reputation: 471

sudo command in Popen

I want to run sudo command from within my python module and provide the password inside the python code. Here are my unsuccessful attempts:

output = subprocess.Popen(['sudo', 'make', 'install'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
print output.communicate('mypass\n')

It asks password from console window (Then I do not want). Then I tried:

output = subprocess.Popen(['sudo', 'make', 'install'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
output.stdin.write('mypass\n')
output.stdin.close()
output.wait()

Again it asks password. Then I tried:

os.popen("sudo make install", 'w').write('mypass')

It again asks for password. What's wrong with my code. I tried all above attempt after doing some search in internet and it seems like they should work.

Upvotes: 2

Views: 2943

Answers (3)

Verma
Verma

Reputation: 966

To add user interactivity you should use pexpect (http://www.noah.org/wiki/pexpect) rather than popen. This will allow your program to to run sudo properly.

Keeping passwords in your script is always a bad idea and allowing access via modification to sudoer especially for something like make is a security hole.

Upvotes: 1

Joe McMahon
Joe McMahon

Reputation: 3382

Another option is to add an entry to /etc/sudoers for the particular command and the particular user.

builduser ALL=NOPASSWD: /usr/bin/make

Edit: It's probably better to wrap the particular command you want in a script, and then allow them sudo access to the script w/o a password; obviously 'make' is fairly dangerous...

Upvotes: 1

jim mcnamara
jim mcnamara

Reputation: 16379

sudo, ssh, sftp are all designed to know if there is a tty attached, so they ask for a password. The reason is that putting passwords in code is a big security violation.

You can use the expect utility to run sudo or ssh and your python code, too...

Use expect in bash script to provide password to SSH command

Upvotes: 2

Related Questions