Using Sudo with Python Script

Using sudo with Python script

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
p = os.system('echo %s|sudo -S %s' % (sudoPassword, command))

Try this and let me know if it works. :-)

And this one:

os.popen("sudo -S %s"%(command), 'w').write('mypass')

How to make python script to run sudo command

-S flag makes sudo read from STDIN

echo mypassword | sudo -S command

But it is better to check if your script is run by root rather than echoing the password.

Cannot run Python script using sudo

By default sudo runs commands in different environment.
You can ask sudo to preserve environment with -E switch.

sudo -E python myScriptName.py

It comes with it's own security risks. So be careful

How to make python script to give sudo prompt my password

I suggest you use Python's "pexpect" module which does just that.
It's based an "expect" and used to automate interactions with other programs.
It's not part of the python standard library mind you, but you do not necessarily need root to install it if you create your own python environment.

Example:

#import the pexpect module
import pexpect
# here you issue the command with "sudo"
child = pexpect.spawn('sudo /usr/sbin/lsof')
# it will prompt something like: "[sudo] password for < generic_user >:"
# you "expect" to receive a string containing keyword "password"
child.expect('password')
# if it's found, send the password
child.sendline('S3crEt.P4Ss')
# read the output
print(child.read())
# the end

More details can be found here:

https://pexpect.readthedocs.io/en/stable/api/index.html

Hope this helps!

Running a python script on a remote server with sudo privileges

The problems in the above script were:

  1. i = child.expect(['[sudo] password for zod1:'])

    Here, [sudo] was not escaped like \[sudo\] hence, pexpect was not able to
    find match since it expects a pattern.

  2. child = pexpect.spawn('sudo su') spawned a new independent process
    instead of continuing with the already spawned process. Using
    child.sendline('sudo su') resolved the issue.

run part of python script as sudo

I would highly recommend putting the sudo parts into a separate script just as the documentation recommended. That approach improves the security posture of your script dramatically as only the part necessary to execute with elevated privileges does (aka "least privilege"--a fundamental security principle).

I haven't read that documentation in detail, but I suspect it also mentions limiting write privileges to the sudo portion of the script as well and any file or resource that it may read from.



Related Topics



Leave a reply



Submit