1

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

1
  • Since Stack Overflow hides the Close reason from you: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. Also see sudo su user -c with arguments not working. Commented Apr 2, 2018 at 0:33

2 Answers 2

2

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())
Sign up to request clarification or add additional context in comments.

Comments

0

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))

8 Comments

I tried "sudo -u testuser -S testpass" it gives o/p as testpass command not found that too it asks for password..
@ArunTracer, can you provide me the python line where you are using this command
#!/usr/bin/python import os,subprocess os.system(' sudo -u mss00d1 -S password) o/p is it asks password after I enter password it gives this sudo: password: command not found
make it like os.system("sudo -u mss00d1 -S password")
thanks, changed as you said.. os.system("sudo -u mss00d1 -S password") but still it asked for password again and says sudo: password: command not found
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.