0

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.

1
  • The command gets stuck and nothing happens Commented Aug 19, 2020 at 17:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I have tried that, and now it is taking the input, however, how can i capture the "Sorry please try again" ?
You have captured it. It's in your output variable, but in output[1] while you just looked at output[0]
thanks so much, what would be a valid method now to confirm if the password is wrong ? the output when i write the wrong password is this [sudo] password for tejas: [sudo] password for tejas: sudo: no password was provided sudo: 1 incorrect password attempt
You can set the environment variable LC_ALL=C to make sure the language is always the same and then e.g. match the substring "incorrect password". Hopefully it's fairly stable over time. Not sure why you'd ever try to do this, but that's a different matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.