Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make python script to give sudo prompt my password

Tags:

python

linux

sudo

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.

like image 461
razrilen Avatar asked Mar 07 '23 08:03

razrilen


1 Answers

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()
like image 186
Shtefan Avatar answered Mar 17 '23 22:03

Shtefan