Skip to content

getpass

The Python getpass module provides portable password input for command-line programs. It reads a password from the terminal without echoing characters back to the screen, which keeps sensitive input from being visible to onlookers or captured in terminal scrollback:

Language: Python
>>> import getpass

>>> password = getpass.getpass("Enter password: ")
Enter password:
>>> password
'seKr3t'

The module also exposes a helper for looking up the current user’s login name.

Key Features

  • Prompts for a password without echoing keystrokes to the terminal
  • Falls back to reading from standard input when echo-free input is unavailable
  • Issues a GetPassWarning when the fallback is used, so insecure environments can be detected
  • Supports an optional masking character for visible keystroke feedback
  • Returns the current user’s login name from environment variables or the system password database

Frequently Used Classes and Functions

Object Type Description
getpass.getpass() Function Reads a password from the terminal with echo disabled
getpass.getuser() Function Returns the login name of the current user
getpass.GetPassWarning Class Warns when password input may be echoed to the terminal

Examples

Prompt for a password with a custom message:

Language: Python Filename: login.py
import getpass

password = getpass.getpass(prompt="Account password: ")
print(f"Received {len(password)} characters")

Run it on the command line:

Language: Shell
$ python login.py
Account password:
Received 7 characters

Display asterisks while the user types, using the echo_char parameter added in Python 3.14:

Language: Python Filename: masked.py
import getpass

password = getpass.getpass(prompt="Password: ", echo_char="*")
print(f"Got {len(password)} characters")

Get the login name of the current user:

Language: Python
>>> import getpass

>>> getpass.getuser()
'john'

The getuser() function checks the LOGNAME, USER, LNAME, and USERNAME environment variables in order and falls back to the system password database if none are set.

Handle the fallback warning when echo-free input is not available:

Language: Python Filename: safe_prompt.py
import getpass
import warnings

with warnings.catch_warnings():
    warnings.simplefilter("error", getpass.GetPassWarning)
    try:
        password = getpass.getpass("Password: ")
    except getpass.GetPassWarning:
        print("Refusing to read password on an insecure terminal.")
        raise SystemExit(1)

Common Use Cases

The most common tasks for getpass include:

  • Prompting for database, API, or service credentials in command-line scripts
  • Asking for an SSH or decryption passphrase without leaking it to the screen
  • Detecting the current user’s login name for personalized output or file paths
  • Guarding interactive tools against insecure terminals by treating GetPassWarning as an error

Real-World Example

Say you need to connect to a remote database. You want a script that reads the username from the environment and prompts for the password interactively so that the secret never appears in shell history or process listings:

Language: Python Filename: db_connect.py
import getpass

def connect(host, user, password):
    print(f"Connecting to {host} as {user}...")
    # Replace with a real database driver call
    return {"host": host, "user": user, "authenticated": bool(password)}

user = getpass.getuser()
password = getpass.getpass(f"Password for {user}: ")
session = connect("db.example.com", user, password)
print(session)

Run it on the command line:

Language: Shell
$ python db_connect.py
Password for john:
Connecting to db.example.com as alice...
{'host': 'db.example.com', 'user': 'john', 'authenticated': True}

The password is collected interactively without being written to the terminal or stored in a variable outside the running process, which keeps the credential out of shell history and command-line arguments.

Tutorial

How to Read User Input From the Keyboard in Python

Reading user input from the keyboard is a valuable skill for a Python programmer, and you can create interactive and advanced programs that run on the terminal. In this tutorial, you'll learn how to create robust user input programs, integrating error handling and multiple entries.

basics best-practices

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 17, 2026