The easy way to execute sudo command in Python using subprocess.Popen
run a command as root using sudo from Python:
1 import subprocess
2
3 def mypass():
4 mypass = '123' #or get the password from anywhere
5 return mypass
6
7 echo = subprocess.Popen(['echo',mypass()],
8 stdout=subprocess.PIPE,
9 )
10
11 sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
12 stdin=echo.stdout,
13 stdout=subprocess.PIPE,
14 )
15
16 end_of_pipe = sudo.stdout
17
18 print "Password ok \n Iptables Chains %s" % end_of_pipe.read()
[via]