Day 9 – Python GetPass/GetUser module
Welcome to Day 9 of 101 Days of DevOps. The topic for today is a python getpass/getuser module.
To understand the use of the getpass module, let start with a simple example.
password=input("Please enter you password: ")
If you save the above code in a file filetest.py and execute it
Please enter you password: abc123
As you can see, when you entered a password will display on the terminal.
getpass() prompts the user for a password without echoing it. The getpass module provides a secure way to handle the password prompts where programs interact via the terminal. The getpass() function is used to prompt users using the string prompt and reads the input from the user as Password.
print("Please enter your password: ")
When you execute the above code, as you can see, now your entered password is not displayed on the console.
Please enter your password:
The input read defaults to “Password: ” is returned to the caller as a string.
my_pass=getpass.getpass(prompt="Enter your password: ")
If you execute the above code, you can see the prompt is now changed to “Enter your password.”
Enter your password:
Similar to getpass(), we have getuser(). This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order and returns the value of the first one, which is set to a non-empty string. If none are set, the login name from the password database is returned on systems that support the pwd module; otherwise, an exception is raised.
In Linux, we have the command whoami, which returns the user name associated with the current effective user id.
Similarly, by using getuser(), we can check the logged-in user
If we execute the above code
- Try to use getpass() when you are prompting for a password, e.g., connecting to a remote machine via ssh or connecting to a remote database.
- Using getuser(), check the logged-in user and depend upon the logged-in user to perform certain tasks.
I am looking forward to you guys joining the amazing journey.