Python offers a useful module for validating user credentials: getpass
.
The getpass
module has two functions used to retrieve a username and a password from the terminal. These can be used in commandline programs that require a user to type in a password (or other sensitive information) without showing or echoing what the user types on the screen.
The module has two functions:
1. getpass.getpass()
. This function has the following signature:
getpass.getpass(prompt='Password: ', stream=None)
The prompt is the message that is displayed on the screen to prompt the user to enter a password. You can override the prompt to suit your needs.
2. getpass.getuser()
. This function returns the login name of the current user.
The password validation program below demonstrates how to use the two functions:
import getpass username = getpass.getuser() while True: password = getpass.getpass(f"Enter password for username {username}: ") if password == 'sekret': print(f"Welcome {username}") break else: print("Incorrect password!")