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.pyimport 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
How to Use the Optional Type Hint
Numpy Argsort - What Is It Doing
How to Avoid Infinite Recursion with Super()
Python Insert Numpy Array into SQLite3 Database
Counting Each Letter's Frequency in a String
Python & Pandas: How to Query If a List-Type Column Contains Something
How to Overlay Two Graphs in Seaborn
What Could Cause a Python Module to Be Imported Twice
Why Results of Map() and List Comprehension Are Different
How to Reverse a Dictionary That Has Repeated Values
How to Combine Multiple Rows into a Single Row with Pandas
How to Check If Stdin Has Some Data
How to Read a File Line-By-Line in Python
How to Obscure a Line Behind a Surface Plot in Matplotlib
Selecting Across Multiple Columns with Python Pandas
Shell Script: Execute a Python Program from Within a Shell Script