Python getpass Module

The getpass module in Python provides a way to securely handle password prompts in a command-line interface. It avoids showing the input on the screen, making it ideal for entering passwords or other sensitive information.

Table of Contents

  1. Introduction
  2. Key Functions
    • getpass
    • getuser
  3. Examples
    • Basic Password Prompt
    • Using getpass in a Script
    • Retrieving the Current User
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The getpass module is used to securely prompt the user for a password without echoing the input back to the console. It is commonly used in scripts and applications that require user authentication or other sensitive input.

Key Functions

getpass

Prompts the user for a password without echoing.

import getpass

password = getpass.getpass('Enter your password: ')
print(f'You entered: {password}')

getuser

Returns the username of the current user.

import getpass

username = getpass.getuser()
print(f'Current user: {username}')

Examples

Basic Password Prompt

import getpass

password = getpass.getpass('Enter your password: ')
print('Password received.')

Example Run:

Enter your password: 
Password received.

Using getpass in a Script

import getpass

def authenticate():
    user = getpass.getuser()
    password = getpass.getpass('Enter your password: ')
    
    # Simulate authentication (replace with actual authentication logic)
    if password == 'secret':
        print(f'Authentication successful. Welcome, {user}!')
    else:
        print('Authentication failed.')

authenticate()

Example Run:

Enter your password: 
Authentication successful. Welcome, <current_user>!

Retrieving the Current User

import getpass

username = getpass.getuser()
print(f'Current user: {username}')

Output:

Current user: <current_user>

Real-World Use Case

Secure User Authentication

You can use the getpass module to prompt for a username and password in a secure way and then authenticate the user.

import getpass

def authenticate_user():
    username = input('Enter your username: ')
    password = getpass.getpass('Enter your password: ')
    
    # Replace with actual authentication logic
    if username == 'admin' and password == 'admin123':
        print('Authentication successful!')
    else:
        print('Authentication failed!')

if __name__ == '__main__':
    authenticate_user()

Example Run:

Enter your username: admin
Enter your password: 
Authentication successful!

Conclusion

The getpass module in Python is used for handling password prompts securely in command-line interfaces. By using this module, you can ensure that sensitive information such as passwords is not displayed on the screen.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare