Python | Prompt for Password at Runtime and Termination with Error Message

Say our Script requires a password, but since the script is meant for interactive use, it is likely to prompt the user for a password rather than hardcode it into the script.

Python’s getpass module precisely does what it is needed. It will allow the user to very easily prompt for a password without having the keyed-in password displayed on the user’s terminal.

Code #1 : How it is done ?



filter_none

edit
close

play_arrow

link
brightness_4
code

import getpass
user = getpass.getuser()
passwd = getpass.getpass()
  
# must write svc_login() 
if svc_login(user, passwd):
    print('Yay !')
else:
    print('Boo !')

chevron_right


In the code above, the svc_login() function is code that is written to further process the password entry. Obviously, the exact handling is application-specific. In the code above getpass.getuser() doesn’t prompt the user for their username. Instead, it uses the current user’s login name, according to the user’s shell environment, or as a last resort, according to the local system’s password database (on platforms that support the pwd module).

To explicitly prompt the user for their username, which can be more reliable, the built-in input function is used.

filter_none

edit
close

play_arrow

link
brightness_4
code

user = input('Enter your username: ')

chevron_right


It’s also important to remember that some systems may not support the hiding of the typed password input to the getpass() method. In this case, Python does all it can to forewarn the user of problems (i.e., it alerts the user that passwords will be shown in cleartext) before moving on.

Executing an External Command and Getting Its Output –

Code #2 : Using the subprocess.check_output() function

filter_none

edit
close

play_arrow

link
brightness_4
code

import subprocess
out_bytes = subprocess.check_output(['netstat', '-a'])

chevron_right


This runs the specified command and returns its output as a byte string. To interpret the resulting bytes as text, add a further decoding step as shown in the code given below –

Code #3 :

filter_none

edit
close

play_arrow

link
brightness_4
code

out_text = out_bytes.decode('utf-8')

chevron_right


If the executed command returns a nonzero exit code, an exception is raised.

Code #4 : Catching errors and getting the output created along with the exit code

filter_none

edit
close

play_arrow

link
brightness_4
code

try:
    out_bytes = subprocess.check_output(['cmd', 'arg1', 'arg2'])
      
except subprocess.CalledProcessError as e:    
    # Output generated before error
    out_bytes = e.output 
    # Return code
    code = e.returncode 

chevron_right


By default, check_output() only returns output written to standard output.

Code #5 : Using stderr argument to get both standard output and error collected

filter_none

edit
close

play_arrow

link
brightness_4
code

out_bytes = subprocess.check_output(
        ['cmd', 'arg1', 'arg2'], stderr = subprocess.STDOUT)

chevron_right


Code #6 : Use the timeout argument() to execute a command with a timeout.

filter_none

edit
close

play_arrow

link
brightness_4
code

try:
    out_bytes = subprocess.check_output(['cmd', 'arg1', 'arg2'], timeout = 5)
except subprocess.TimeoutExpired as e:
    ...

chevron_right


Normally, commands are executed without the assistance of an underlying shell (e.g., sh, bash, etc.). Instead, the list of strings supplied is given to a low-level system command, such as os.execve(). For command to be interpreted by a shell, supply it using a simple string and give the shell=True argument. This is sometimes useful if trying to get Python to execute a complicated shell command involving pipes, I/O redirection, and other features as shown below –
Code #7 :

filter_none

edit
close

play_arrow

link
brightness_4
code

out_bytes = subprocess.check_output(
        'grep python | wc > out', shell = True)

chevron_right


Executing commands under the shell is a potential security risk if arguments are derived from user input. The shlex.quote() function can be used to properly quote arguments for inclusion in shell commands in this case.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.