The Python Oracle

running a command as a super user from a python script

This video explains
running a command as a super user from a python script

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Question
01:53 Accepted answer (Score 22)
02:06 Answer 2 (Score 29)
02:41 Answer 3 (Score 16)
03:16 Answer 4 (Score 13)
04:01 Thank you

--

Full question
https://stackoverflow.com/questions/5675...

Answer 3 links:
[subprocess]: https://docs.python.org/3/library/subpro...
[subprocess]: https://docs.python.org/3/library/subpro...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #subprocess #sudo

#avk47



ANSWER 1

Score 34


Try:

subprocess.call(['sudo', 'apach2ctl', 'restart'])

The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.

If you don't define them, then it grabs sys.stdout, etc...




ACCEPTED ANSWER

Score 24


Try giving the full path to apache2ctl.




ANSWER 3

Score 19


Another way is to make your user a password-less sudo user.

Type the following on command line:

sudo visudo

Then add the following and replace the <username> with yours:

<username> ALL=(ALL) NOPASSWD: ALL

This will allow the user to execute sudo command without having to ask for password (including application launched by the said user. This might be a security risk though




ANSWER 4

Score 16


I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for more information.

What we are doing here is echoing the password and then using pipe we pass it on to the sudo through '-S' argument.

#!/usr/bin/env python
import subprocess

sudo_password = 'mysecretpass'
command = 'apach2ctl restart'
command = command.split()

cmd1 = subprocess.Popen(['echo',sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)

output = cmd2.stdout.read().decode() 

Note - For obvious reasons don't store passwords directly in code rather use environment variables or a different safer method to get the same