getpass() and getuser() in Python (Password without echo)


When you create some python programs that need password protection before it can run, we take the help of the getpass() and getuser() modules. They have a variety of functionalities that can be used to manage password protection as well as password retrieval etc. In this article, we will see how to type in the password with and without echoing it back on the screen. Below are the different ways it is handled.

With Prompt

The below code is saved to a file (logon.py). The getpass() function prints a prompt then reads input from the user until they press return

Example

 Live Demo

import getpass
try:
   pwd = getpass.getpass()
except Exception as err:
   print('Error Occured : ', err)
else:
   print('Password entered :', pwd)

Output

Running the above code gives us the following result −

$ python logon.py
Password:
Password entered: abracadbra

With Security Question

Next, we can enhance the code to prompt the user with a security question. This question helps the user to recall the password.

Example

import getpass
pwd = getpass .getpass(prompt = 'What is your favorite colour?')
if pwd == 'Crimson':
   print('You are in!')
else:
   print('Try Again')

Output

Running the above code gives us the following result −

$ python logon.py
'What is your favorite colour?
You are in!

Displaying Login name

Sometimes we need to know the login name which we are using to run the script. This is achieved by using the getuser() function.

Example

import getpass
user = getpass.getuser()
while True:
   pwd = getpass.getpass("User Name : ",user)
   if pwd == 'Crimson':
      print("You are in!")
   else:
      print("The password you entered is wrong.")

Output

Running the above code gives us the following result −

User Name: user1
You are in !

Updated on: 17-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements