do sudo su - user in python script - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: do sudo su - user in python script (/thread-9333.html) |
do sudo su - user in python script - aruntracer - Apr-02-2018 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 RE: do sudo su - user in python script - wavic - Apr-02-2018 Use subprocess module. RE: do sudo su - user in python script - Gribouillis - Apr-02-2018 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) |