Arunkumar Arjunan
Arunkumar Arjunan

Reputation: 382

how to use sudo su - username in python script and pass password to it

I got frustrated, after searching in all available forums for this answer.. I want to use sudo su - username inside a python script and also I need to assign password as well to it in script itself.

sudo su - username

Please let me know if this is possible or not.

Thanks

Upvotes: 1

Views: 6727

Answers (2)

Himanshu Kumar
Himanshu Kumar

Reputation: 21

You can simply use subprocess in the following way:

sudoPassword = "your sudo password"
command      = "your command"

commandFinal = "echo " + sudoPassword + " | sudo -S " + command
        output = subprocess.Popen(commandFinal, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out = (output.communicate())
        out = (out[0].strip())

Upvotes: 2

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

Please don't be frustrated we are here to help you. Use below command in your python script:-

 sudo -u USER -S password

Suppose you are executing a second script as sudo:-

 echo $password | sudo -u USER -S ./yourscript.sh

In python script use like below:-

command = 'yourcommand'
os.system('echo %s|sudo -u %s -S %s' % (sudoPassword, user, command))

Also simply use like below without user

os.system('echo %s|sudo -S %s' % (sudoPassword, command))

os.system('echo %s|sudo -S ' % (sudoPassword))

Upvotes: 0

Related Questions