Python package – “getpass”

In Networking world, one of the most common thing user would like to do is to access devices over SSH connection. As we know SSH is an encrypted protocol and require users to prove authenticity which in turn requires a password.

Before I will start demonstrating – lets understand how to take input from user in Python. Refer to below code for reference

# Let us demonstrate this without "getpass"
# Python program showing a use of raw_input()
USERNAME = input("Enter your login name : ")
print(USERNAME)
$ python ssh_input.py
Enter your login name : MRCISSP
MRCISSP

If we observe the above output; entered username can be clearly seen on the screen. Many similar programs that interact with the user via the terminal need to ask the user for password values without showing what the user types on the screen. The “getpass” module provides a portable way to handle such password prompts securely. Let’s walk through some examples to understand its implementation.

# Lets understand the purpose of "getpass" package
# Primary Goals
#       1. Reading password without display
# Our objective is to create a Python program name "ssh_input" which accept these inputs
#       1. Login user : mrcissp
#       2. Login password : pythonfornetworkengineers
# & ensure that "Login password" must not be visible on console.

# Let us demonstrate this without "getpass"
# Python program showing a use of raw_input()
USERNAME = input("Enter your login name : ")
print('Username entered is ' + USERNAME)

# A simple Python program to demonstrate  getpass.getpass() to read password
import getpass

try:
    PASSWORD = getpass.getpass()
except Exception as error:
    print('ERROR', error)
else:
    print('Password entered is', PASSWORD)
$ python ssh_input.py
Enter your login name : mrcissp
Username entered is mrcissp
Password:
Password entered is pythonfornetworkengineers

As you can observe from the above output – password is actually hidden from the console.

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.