Search code examples
pythonlinuxmacossudo

Python- How To Get Output Of Sudo Command Using Popen


sudo command validates the password of the user against the user name. I am writing a simple program which checks if the user's input is valid according to the sudo command. I am using the -S tag in order to pass an input externally, and i am using Popen() to run the script:

import getpass
import subprocess
import time

password = getpass.getpass()
proc = subprocess.Popen('sudo -k -S -l'.split(), stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output = proc.communicate(password.encode())
print(f'This is the value of the output {output[0]}')

If the user inputs the wrong password in the getpass.getpass() I need to validate it against the actual user password. In this case, sudo should output Sorry Please Try Again. Could someone please let me know how I can read that error?

When I run this in the terminal:

➜  Desktop python3.8 test.py
Password: 
Sorry, try again.
This is the value of the output b''

Thanks, cheers and I really appreciate your help.


Solution

  • The Python Documentation says:

    Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE.

    So use

    proc = subprocess.Popen(['sudo', '-S', '-l'], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    

    to allow writing a password with communicate, otherwise it just waits for you to enter it on the terminal (without a prompt since it's being captured).

    Any error messages are available in the output variable, specifically output[1] which corresponds to stderr.