It is quite common that you need to grab a logged-in user name and ask for the password from a user on an application launch.
The biggest question that comes here is — Can we grab password from user in plain text? Can password input be in plain text which can be seen while entering?
Of course not. As a password is considered one of the most sensitive data, it can not be exposed so lightly. Due to its sensitivity, either user input has to be masked or it had taken in invisible form.
Let’s learn about it in more detail.
Like every other Python application, here also we need to import the required module/package and that isgetpass.
Required Package
getpassallows us to prompt for password without having the password displayed on screen or on user’s terminal. Below is the command to installgetpass:
pip install getpass
Read User Name
getpasshas a function namedgetuser(), which gives us the login name of a currently logged-in user.
userName = getpass.getuser()
If you want to prompt a user for a user name, instead of logged-in, then you can go with the traditional way of getting input as shown below:
userName= input(‘Enter user name: ‘)
Read Password
Similar togetuser(), we havegetpass()function, which helps us with grabbing password from user without showing what is keyed-in. Here is one line to grab the password:
password = getpass.getpass()
Don’t forget to importgetpassmodule, before making a call to any of these functions.
If you would like to have a complete code walk-through, do check out my YouTube video here.