Python | Prompt for Password at Runtime and Termination with Error Message
Last Updated :
12 Jun, 2019
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 ?
Python3 1==
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.
Python3 1==
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
Python3 1==
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 :
Python3 1==
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
Python3 1==
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
Python3 1==
out_bytes = subprocess.check_output(
['cmd', 'arg1', 'arg2'], stderr = subprocess.STDOUT)
Code #6 : Use the timeout argument() to execute a command with a timeout.
Python3 1==
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 :
Python3 1==
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.
Similar Reads
getpass() and getuser() in Python (Password without echo) getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal. getpass module provides two functions :Using getpass() function to prompt user password Syntax: getpass.getpass(
2 min read
Python | Random Password Generator using Tkinter With growing technology, everything has relied on data, and securing this data is the main concern. Passwords are meant to keep the data safe that we upload on the Internet. An easy password can be hacked easily and all personal information can be misused. In order to prevent such things and keep th
4 min read
GUI to generate and store passwords in SQLite using Python In this century there are many social media accounts, websites, or any online account that needs a secure password. Â Often we use the same password for multiple accounts and the basic drawback to that is if somebody gets to know about your password then he/she has the access to all your accounts. It
8 min read
Create a Random Password Generator using Python In this article, we will see how to create a random password generator using Python. Passwords are a means by which a user proves that they are authorized to use a device. It is important that passwords must be long and complex. It should contain at least more than ten characters with a combination
5 min read
Storing passwords with Python keyring In this article, we will see how to store and retrieve passwords securely using Python's keyring package. What is a keyring package? keyring package is a module specifically designed to securely store and retrieve passwords. It is like the keychain of MacOS, using this module and Python code we can
2 min read
How to Build a Simple Auto-Login Bot with Python In this article, we are going to see how to built a simple auto-login bot using python. In this present scenario, every website uses authentication and we have to log in by entering proper credentials. But sometimes it becomes very hectic to login again and again to a particular website. So, to come
3 min read
Create a Yes/No Message Box in Python using tkinter Python offers a number Graphical User Interface(GUI) framework but Tk interface or tkinter is the most widely used framework. It is cross-platform which allows the same code to be run irrespective of the OS platform (Windows, Linux or macOS). Tkinter is lightweight, faster and simple to work with. T
4 min read
Python | Reraise the Last Exception and Issue Warning Problem - Reraising the exception, that has been caught in the except block. Code #1: Using raise statement all by itself. Python3 1== def example(): try: int('N/A') except ValueError: print("Didn't work") raise example() Output : Didn't work Traceback (most recent call last): File "", lin
2 min read
How to Create a Simple Messagebox in Python Python has the capability to create GUI applications using libraries like tkinter and PyQt5. These libraries provide easy-to-use methods for creating various GUI elements, including messageboxes. In this article, we will explore both this approaches to create a simple messagebox in Python. Create A
2 min read
How to Navigating the "Error: subprocess-exited-with-error" in Python In Python, running subprocesses is a common task especially when interfacing with the system or executing external commands and scripts. However, one might encounter the dreaded subprocess-exited-with-error error. This article will help we understand what this error means why it occurs and how to re
4 min read