0

I am trying to use su linux command in a python script along with getpass and subprocess python standard libraries to switch to a new user before executing my script. I am using this function:

import subprocess
import getpass

def ask_passwd():
    pw = getpass.getpass(prompt='Please insert the passwd to use the auto api:') # prompt the user for a passwd
    print pw
    command = "su new_user"
    p = subprocess.Popen(command.split(), stdin=subprocess.PIPE)
    p.communicate(pw) # communicate the passwd

def main():
    # code here    

if __name__ == '__main__':
    ask_passwd()
    main()

When executing the script the main code works but not the su command. Here what I get back:

Please insert the passwd to use the auto api:
pass
su: must be run from a terminal

Any help? thanks

diegus
  • 1,168
  • 2
  • 26
  • 57
  • 2
    Possibly answered here http://stackoverflow.com/questions/8025294/changing-user-in-python – Karim Tabet Oct 10 '16 at 08:31
  • @karimtabet Why does not work with `subprocess` library? According with the python documentation (https://docs.python.org/2/library/subprocess.html) `subprocess` should replace the older `os.system` module used in the answer you are referring to – diegus Oct 10 '16 at 08:39
  • Do you want to run the shell with the user new_user or run some commands in background with that user? – Jose Raul Barreras Oct 10 '16 at 09:30
  • @JoseRaulBarreras I would like the new_user being the user that runs the main code, i.e. the main() function. So I guess it would be to run the shell with the new user. – diegus Oct 10 '16 at 10:03
  • @diegus, the new_user can change over the time? – Jose Raul Barreras Oct 10 '16 at 15:34
  • @JoseRaulBarreras not sure what you mean..I imagine you log into the system with user_A and when executing the python script you are first prompt for a passwd to switch to new_user. The script is executed, then when it is over it goes back to user_A – diegus Oct 11 '16 at 07:45
  • @diegus Were you able to figure this out? – Aniruddh Apr 01 '17 at 02:50

1 Answers1

0

you may use subprocess.popen. There is an example

import subprocess

sudo_password = 'yourpassword'
command = '-i -u youruser \n id'
command = command.split()

cmd1 = subprocess.Popen(['echo', sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo', '-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)


output = cmd2.stdout.read()

print output