Change to Sudo User Within a Python Script

Change to sudo user within a python script

Use Tcl and Expect, plus subprocess to elevate yourself. So basically it's like this:

sudo.tcl

spawn sudo
expect {
"Password:" {
send "password"
}
}

sudo.py

import subprocess
subprocess.call(['tclsh', 'sudo.tcl'])

And then run sudo.py.

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

How to switch users using a script?

sudo can execute commands as any user.

You can do:

sudo -u oneuser /var/lib/myscript
sudo -u anotheruser /var/lib/myscript

Also see sudo man page.

Note that however runs the sudo must be root or have necessary permission mappings in /etc/sudoers.



Related Topics



Leave a reply



Submit