In many of our Python programs, we need to get secret keys, pass-phrases or password for a secret transaction or identifying a user if they are authorized to do something. Many things need to be taken care of while accepting the keys, that the phrase should not be echoed back to the screen, disabling the echoing of statements etc. With Python getpass
module, all of these features come in-built. Let’s use this simple module in examples and see how this can be put to use.
Table of Contents
Python getpass module
We will start with a simple way of accepting keys in Python examples and gradually customising the user experience with a custom prompt for the user. Finally, we will see how we can stream the password to other places like a file instead of the terminal. Let’s get started.
Python getpass example
Let’s start experimenting the module with a very basic example of getting a password from the user on the terminal:
import getpass
try:
pwd = getpass.getpass()
except Exception as ex:
print('Error Occured : ', ex)
else:
print('Entered secret :', pwd)
Let’s see the output for this program:
The password is the deafult prompt for the user. In next example, we will be customising it.
Python getpass custom prompt
To prompt a user with your own message, just provide a String argument in the getpass()
function:
import getpass
pwd = getpass.getpass(prompt = 'Which is your favorite place to go?')
if pwd == 'JournalDev':
print('Ofcourse!')
else:
print('Where is that?')
Let’s see the output for this program:
This function is useful when you need to ask for secret passphrases apart from explicit passwords.
Python getpass with other stream
Disabling terminal echoes of the password and diverting input to any other stream is also possible with getpass()
function. Just pass the stream
to the function as well:
import getpass
import sys
pwd = getpass.getpass(stream=sys.stderr)
print('You entered:', pwd)
Let’s see the output for this program:
Getting passwords without Terminal
When you are working on a Unix system, getpass()
needs a tty which can be controlled via termios. This is needed so that input echoing is disabled.
Let’s execute our first sample code on a non-Unix machine:
echo "not dark" | python3 getpass_defaults.py
Let’s see the output for this program:
As we excuted the program on a non-Unix machine, there was no difference to the output. Otherwise, you would have simply seen
not dark
on the screen.Read more about teletype terminals here.
Conclusion
In this lesson, we studied a very simple way with which we can accept secret values in our Python programs and stream them to the terminal or any other possible streams and pipes.
Read more Python posts here.