Search code examples
pythonlinuxsudo

How to make python script to give sudo prompt my password


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.


Solution

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