Open In App

Python getpass module

Last Updated : 23 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

When we use terminal based application with some security credentials that use password before execution the application, Then It will be done with Python Getpass module. In this article we are going see how to use Getpass module.

Getpass module provides two function:

  • getpass.getpass()
  • getpass.getuser()

getpass()

In many programs we need a secure the data or program then this case we use some secret key or passwords to identifying the users. Using getpass() it is possible to accept the password in python program.

Python3




import getpass
  
pwd = getpass.getpass(prompt = 'Enter the password')
if pwd == 'Admin':
    print('Unlock!')
else:
    print('You entered wrong password')


Output:

Let’s understand this module some example:

getpass with no prompt:

In this example we will see how to get password from users and return the same password with no prompt.

Python3




import getpass
  
pwd = getpass.getpass()
print("You entered: ", pwd)


Output:

getpass with prompt:

If user want some message before login like security question then we will use prompt attributes in getpass.

Python3




import getpass
  
pwd = getpass.getpass(prompt = 'What is you last Name: ')
if pwd == 'Kumar':
    print('Unlock! Welcome kumar')
else:
    print('You entered wrong Name')


Output:

getpass with other stream:

This function allow us to stream the password a user enter.

Python3




import getpass
import sys
  
pwd = getpass.getpass(stream = sys.stderr)
print('Entered Password: ', pwd)


Output:

getuser()

This function return system login name of the user. It checks the environment variable of your computer and fetch the user name and return as a string and if it can not able to find the environment variable then exception is raised.

Example 1:

Here we will get username of our computer with getuser().

Python3




import getpass
  
print(getpass.getuser())


Output:

Example 2:

Here we will get username and password with getuser() and getpass().

Python3




import getpass
   
user_name = getpass.getuser()
pass_word = getpass.getpass("Enter password: ")
   
print("User name: ", user_name)
print("Your password :", pass_word)


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads