How to take Password input in Python

Did you know? There is a python module in Python Standard Library called getpass. The purpose of this library is to securely take input from user!

The module is very handy for sensitive inputs such as passwords / keys or any kind of credentials.

Simplest example of getpass could be this:

import getpass
password = getpass.getpass("enter password:")

The code is pretty straight forward! This password prompt will act similarly to unix password prompt, and it won’t echo user inputs (i.e. the key presses) hence, the password you type won’t be visible to end users. The best thing about this module is it is cross platform. So, you can use it on Windows, Linux or Mac.

There are only two functions listed in  The official documentation.
These are:

  •  getpass() – password prompt
  • getuser() – collects username from different environment variables

But, there are more than that, let me show you 😉

>>> import getpass
>>> dir(getpass)
['GetPassWarning', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_raw_input', 'contextlib', 'fallback_getpass', 'getpass', 'getuser', 'io', 'os', 'sys', 'termios', 'unix_getpass', 'warnings', 'win_getpass']

If you inspect carefully you will notice there are two more functions listed in the __dir__

  • unix_getpass( )
    unix_getpass(prompt='Password: ', stream=None)
     Prompt for a password, with echo turned off.
     
     Args:
     prompt: Written on stream to ask for the input. Default: 'Password: '
     stream: A writable file object to display the prompt. Defaults to
     the tty. If no tty is available defaults to sys.stderr.
     Returns:
     The seKr3t input.
     Raises:
     EOFError: If our input tty or stdin was closed.
     GetPassWarning: When we were unable to turn echo off on the input.
     
     Always restores terminal settings before returning.
  • win_getpass( )
    Help on function win_getpass in module getpass:
    
    win_getpass(prompt='Password: ', stream=None)
     Prompt for password with echo off, using Windows getch().

The docstring of these functions tells it all doesn’t it? 🙂

Note that, the win_getpass function uses the Windows getch() so, it requires the msvcrt module.

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.