Python Getpass Module: A Simple Guide + Video

5/5 - (4 votes)
Python Getpass Module: Explanation | How To | Examples

The Python getpass module provides portable password input functionality and allows you to accept an input string in a command-line interface (CLI) without the string being typed from being visible (echoed) in the interface.

The getpass module also includes a getuser function for retrieving a username from the relevant environment variables.

In this getpass Python tutorial, I’ll show you how to install getpass and use the functionality and then explain some of the background concepts and FAQs.

How Do I Install Python Getpass?

The getpass module is part of the Python Standard Library, filed under the ‘Generic Operating System Services’ category.

This means you will most likely already have it in your Python installation and won’t need to install it. However, it’s not a built-in function so you will need to import it to use it.

Like this:

import getpass

Syntax & Example

Here’s the syntax and example to illustrate how to use the Python getpass module:

getpass.getpass(prompt='Password: ', stream='None')

The prompt is an optional keyword argument for what the user will see in the command-line interface to prompt their password input. The default value is 'Password: ' which will show if you don’t offer an alternative prompt.

The stream keyword argument is for you to specify the stream that the prompt is written to (only used on Unix). If you don’t specify an alternative stream, the default value of None will be passed and the getpass() function will choose the most appropriate stream for you.

Example:

import getpass

users = {
   'nick': '12345'
}

usr = input('Username: ')

if usr in users:
    passwrd = getpass.getpass('Enter Password: ')
    if passwrd == users[usr]:
        print('Access approved')
    else:
        print('Incorrect password, access denied')
else:
    print(f'User not found: {usr}')

Outputs:

The code prompts the user to enter values at two different points β€˜Username: β€˜ and β€˜Enter Password’ and the code output will be different depending on the inputs

Username Entered / Password Entered : Output
nick / 1234 : Access approved
nick / [anything other than β€˜1234’] : Incorrect password, access denied
[anything other than β€˜nick’] / n/a : User not found: {[user entered]} 

Explanation:

In this example, we start off with a dictionary with the recorded usernames and corresponding passwords.

❗ Attention: Passwords should not be stored in plaintext in a database like this but this is just a quick illustrative example).

First, we ask for a username using the standard input (I’ll discuss an alternative to this below) and then if the username is found in the dictionary, we ask for the corresponding password using the getpass() function.

πŸ’‘ Note: we have used the optional prompt parameter to enter our custom password prompt Enter Password:  

The program then checks if the password entered matches the one corresponding to the user as recorded in the dictionary.

If the password matches the username then a success message is printed but if one is incorrect then a fail message is printed.

Use Cases

The getpass module is just for accepting a string in a CLI (Command Line Interface) without having that string echo into the CLI as it is typed.

This could be a basic first step of security for any CLI app. It’s not a full security solution so if you need to protect sensitive data you should implement further layers of security.

The module is designed for accepting passwords but you could use it to accept any strings that you want to hide, such as secret answers to a quiz.

GetPassWarning

If for some reason, the getpass() function can’t prevent the CLI from echoing the password, the GetPassWarning will be triggered to warn the user.

That would look something like this:

GetPassWarning: Can not control echo on the terminal.
passwd = fallback_getpass(prompt, stream)
Warning: Password input may be echoed.

Function getuser()

The getuser() function is the second function available in the getpass module. It’s used to get a username from one of four existing environment variables:

  • LOGNAME
  • USER
  • LNAME
  • USERNAME

If none of those environment variables contains a username string, the function will attempt to get the username from the 'Password Database' pwd module instead.

Here’s an example of getuser() in action:

# USER environment variable already set by the os
# os.environ['USER'] = 'nick'

import getpass

users = {
   'nick': '12345'
}

usr = getpass.getuser()

if usr in users:
    print(f'Welcome back, {usr}')

Output:

Welcome back, nick

Explanation:

In this code sample, the getuser() function attempts to extract a username and then we check if that username is in our dict. If it is then we print the message 'Welcome back, [username]' 


FAQ Getpass

That wraps up the explanation for the getpass module. In the rest of the article, I’ll go through some related FAQs and background information.

What is a Stream in Python Getpass?

A stream in computing is something that can transfer data between two endpoints; a source and an outflow or ‘input‘ and ‘output.’

The three standard input/output (I/O) streams are stdin (standard input), stdout (standard output) and stderr (standard error).

Originally these were physical connections but in modern computing and software, they are abstracted.

Streams are like files and you can read/write data from the streams like you can with files. They’re relevant to getpass because the module will attempt to use alternate streams for reading and writing the data if the default stream/s are not available.

As per the getpass docs:

On Unix, the prompt is written to the file-like object stream using the replace error handler if needed. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows).

If echo free input is unavailable getpass() falls back to printing a warning message to stream and reading from sys.stdin and issuing a GetPassWarning.

What is a tty in Python?

Originally, a tty was a short name for a physical ‘teletypwriter’ device that connected a typewriter to a teletape printer.

These days, a tty is used to describe any text input/output environment which could be either physical or in software and is roughly equivalent to the term ‘terminal.’

A ‘console‘ is a physical version of a terminal.

A ‘terminal emulator‘ is a software version of a physical terminal. This is probably what you’re used to working with on your computer.

A ‘shell‘ is a command-line interpreter which runs on the terminal.

This can help to disambiguate these terms but note that often they’re used interchangeably.

What is getpass in Python?

Getpass is a module for masking a password input so it is not echoed to the command line interface as it is being typed. The module also provides support for prompting the password input and retrieving the username of the current user.

Is Getpass in Python Standard Library?

Yes, it is. However, it is not a built-in function so you will still need to import it to use it in your code. Like this: import getpass


Programmer Humor

Q: How do you tell an introverted computer scientist from an extroverted computer scientist?

A: An extroverted computer scientist looks at your shoes when he talks to you.