Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rochacbruno/1005957 to your computer and use it in GitHub Desktop.
Save rochacbruno/1005957 to your computer and use it in GitHub Desktop.
Executar comando do OS (unix) como root usando sudo no Python - run a command as root using sudo from Python
import subprocess
echo = subprocess.Popen(['echo','123'],
stdout=subprocess.PIPE,
)
sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
stdin=echo.stdout,
stdout=subprocess.PIPE,
)
end_of_pipe = sudo.stdout
print "Iptables Chains:"
print end_of_pipe.read()
import subprocess
echo = subprocess.Popen(['echo','123'],
stdout=subprocess.PIPE,
)
sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
stdin=echo.stdout,
stdout=subprocess.PIPE,
)
end_of_pipe = sudo.stdout
print "Iptables Chains:"
print end_of_pipe.read()
import os
def mypass():
mypass = '123'
return mypass
def command(cmd):
text = os.popen( "echo %s | sudo -S %s" % (mypass(),cmd) ).read()
return text
print command('iptables -L')
import os
def mypass():
mypass = '123'
return mypass
def command(cmd):
os.popen( "echo %s | sudo -S %s" % (mypass(),cmd) )
f = open("log.txt", "r")
text = f.read()
f.close()
return text
command('iptables -L > log.txt')
import subprocess
def mypass():
mypass = '123' #or get the password from anywhere
return mypass
echo = subprocess.Popen(['echo',mypass()],
stdout=subprocess.PIPE,
)
sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
stdin=echo.stdout,
stdout=subprocess.PIPE,
)
end_of_pipe = sudo.stdout
print "Password ok \n Iptables Chains %s" % end_of_pipe.read()
@eshizhan
Copy link

waaa, is realy easy, ths;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment