Python Forum

Full Version: do sudo su - user in python script
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to use sudo su - username inside a python script and also I need to assign password(I won't hardcode this instead this will come from user input from GUI) as well to it in script itself.

Manual steps:
1.usera$ sudo su - userb
2.usera$ "Entering password"
3.userb$ ./file.sh

I want to do the above steps inside a python script.

I have tried with the below but it switch's to userb and it will halt and wont run ./file.sh , when I exit it run's file.sh

#!/usr/bin/python
import os
os.system("echo password| sudo -S su - userb")

os.system("sudo -S su - userb")

os.system("file.sh")

Please help!
Thanks
Use subprocess module.
I have an old snippet in my notes:
import getpass
import subprocess as sp
COMMAND = ['ls']
mypass = getpass.getpass('This needs administrator privileges: ')

proc = sp.Popen(['sudo', '-kS'] + COMMAND, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
proc.stdin.write(mypass + '\n')
o, e = proc.communicate()

if proc.recurncode:
    print('command failed')
else:
    print('success')
print(o)
print(e)