I'm writing a script in python 3.6 that uses many sudo commands. The script runs on linux machines, as my user. The script is creating a sort of a report, doing ssh to many servers and running commands like lsof.
I need a way of making python give my password any time I use sudo. Obviously in the first time I'll enter my password, and it can be saved in the script's memory.
I've been using python subprocess to run my sudo commands, for example:
cmd = SSH + '-t ' + source + " ' " + SUDO + "-k " + LSOF + "-p " + pid + " ' " output = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
(out,error) = output.communicate()
Is it possible?
constraints:
Root kit is not allowed
Running the script with sudo is not an option, since the script does ssh to many servers, and for security reasons I'm not allowed to do so.
Can't change anything in sudoers file.
Spent some hours to figure out how to do it with subprocess.
So enjoy:
import getpass
import subprocess
sudo_password = getpass.getpass(prompt='sudo password: ')
p = subprocess.Popen(['sudo', '-S', 'ls'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
try:
out, err = p.communicate(input=(sudo_password+'\n').encode(),timeout=5)
except subprocess.TimeoutExpired:
p.kill()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With