Ruan Bekker's Blog

From a Curious mind to Posts on Github

Using Getpass in Python to Accept Passwords From Stdin Without Echoing It Back

Using raw_input in python expects standard input, which echo’s it back after enter is executed, below is an example:

1
2
3
4
5
>>> word = raw_input("What is the word? \n")
What is the word?
football
>>> print(word)
football

Using getpass, the standard input gets masked, like you would expect when entering a password, like below:

1
2
3
4
5
>>> from getpass import getpass
>>> word = getpass()
Password:
>>> print(word)
rugby

Changing the default prompt:

1
2
3
4
>>> word = getpass(prompt='What is your name? ')
What is your name?
>>> print(word)
Ruan

Creating a Simple Insecure Password Verification App:

1
2
3
4
5
6
7
from getpass import getpass

password = getpass()
if password.lower() == 'simplepass':
    print 'Password Correct'
else:
    print 'Password Failed'

Testing it, by first entering a incorrect string, then the correct one:

1
2
3
4
5
6
7
$ python auth-check.py
Password:
Password Failed

$ python auth-check.py
Password:
Password Correct

You definitely don’t want to hard code the credentials in your app, but you get the idea.

Comments