Get User Name And Password At Runtime Using Python

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 is getpass.

Required Package

getpass allows us to prompt for password without having the password displayed on screen or on user’s terminal. Below is the command to install getpass:

pip install getpass

Read User Name

getpass has a function named getuser(), 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 to getuser(), we have getpass() 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 import getpass module, 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.


Similar Articles