Open In App

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

Last Updated : 12 Jun, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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 ?




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


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.




user = input('Enter your username: ')


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




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


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 :




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


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




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 


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

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




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


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




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


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 :




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


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads