Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
getpass() and getuser() in Python (Password without echo)
The getpass module in Python provides secure password input functionality without displaying typed characters on screen. This is essential for applications requiring password authentication where you need to hide sensitive input from shoulder surfing or screen recording.
Basic Password Input with getpass()
The getpass() function prompts for a password and reads input without echoing it to the terminal ?
import getpass
try:
pwd = getpass.getpass()
except Exception as err:
print('Error Occurred:', err)
else:
print('Password entered:', pwd)
The output of the above code is ?
Password: Password entered: abracadabra
Custom Security Prompt
You can customize the prompt to show a security question that helps users recall their password ?
import getpass
pwd = getpass.getpass(prompt='What is your favorite color? ')
if pwd == 'Crimson':
print('Access granted!')
else:
print('Access denied. Try again.')
The output of the above code is ?
What is your favorite color? Access granted!
Getting Current Username with getuser()
The getuser() function returns the current login username, useful for personalized authentication ?
import getpass
user = getpass.getuser()
print(f"Current user: {user}")
pwd = getpass.getpass(f"Enter password for {user}: ")
if pwd == 'secret123':
print(f"Welcome {user}!")
else:
print("Invalid password.")
The output of the above code is ?
Current user: johnsmith Enter password for johnsmith: Welcome johnsmith!
Key Features
| Function | Purpose | Returns |
|---|---|---|
getpass() |
Secure password input | String (password) |
getuser() |
Get current username | String (username) |
Complete Login System Example
import getpass
def secure_login():
username = getpass.getuser()
print(f"Login for user: {username}")
max_attempts = 3
attempts = 0
while attempts < max_attempts:
try:
password = getpass.getpass("Enter password: ")
if password == "python123":
print("Login successful!")
return True
else:
attempts += 1
remaining = max_attempts - attempts
if remaining > 0:
print(f"Invalid password. {remaining} attempts remaining.")
else:
print("Maximum attempts exceeded. Access denied.")
except KeyboardInterrupt:
print("\nLogin cancelled.")
return False
return False
# Run the login system
secure_login()
Conclusion
The getpass module provides essential security features for Python applications requiring password authentication. Use getpass() for hidden password input and getuser() to identify the current user, ensuring sensitive data remains protected during input.
