I'm trying to run Python file with root access with php index
in php there is :
passthru('python /home/register/register.py '. $_POST['username'] . ' example.com ' . $_POST['password'] . ' ' . $_POST['email'] . ' ' . $ip . ' 1 2>&1');
and in Python file there is:
os.popen("sudo -u root -p password /sbin/ejabberdctl register %s %s %s" % (user,domain,password)).read()
is there any command with Python to login with root user then do command like : ls or mkdir
thnx.
2 Answers 2
from subprocess import PIPE,Popen
p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)
p.stdin.write("password\n")
p.stdin.write("mkdir foo\n")
p.stdin.write("id -u")
To see output use communicate:
from subprocess import PIPE,Popen
p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)
p.stdin.write("password\n")
p.stdin.write("ls -la\n")
p.stdin.write("/usr/bin/pip list\n")
p.stdin.write("id -u")
print(p.communicate()[0])
But be very sure you know what commands you are running.
5 Comments
I recently published a project that allows PHP to obtain and interact with a real Bash shell (as user: apache/www-data or root if needed). Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
//Setting the second argument in getShell():
//true will return a shell with root
//false will return a shell with the php execution user
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd("mkdir -p /some/path");
$return2 = $shell->exeCmd("ls --color=none /some/path");
notice the ls command has a switch called --color=none, that is needed because the bash shell will return color information as odd chars, the switch prevents it.
$_POSTvariables without any sanitation to Python (and then to sudo! Again without sanitation) is a huge security hole.