Day 9–101 Days of DevOps — Python GetPass/GetUser module
Welcome to Day 9 of 101 Days of DevOps. The topic for today is a python getpass/getuser module.
To view the complete course, please check the below url.
For more info, register via the below link
YouTube Channel link
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
python3 filetest.pyPlease 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.
import getpassprint("Please enter your password: ")my_pass=getpass.getpass()
When you execute the above code, as you can see, now your entered password is not displayed on the console.
python3 getpasstest.pyPlease enter your password:Password:
The input read defaults to “Password: ” is returned to the caller as a string.
import getpassmy_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.”
python3 getpasstest.pyEnter your password:
getuser()
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.
$ whoamiec2-user
Similarly, by using getuser(), we can check the logged-in user
import getpassprint(getpass.getuser())
If we execute the above code
python3 get_user.pyec2-user
Assignment:
- 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.