getpass () and getuser () in Python (no echo password)

Python Methods and Functions

This module provides two functions:

  1. GetPass ()
     getpass.  getpass  (prompt = 'Password:', stream = None) 

    The getpass () function is used to prompt users with a string prompt and reads user input as a password. The input is read from "Password:" and returned to the caller as a string.

    Let's take a look at some examples to understand its implementation.

    Example 1: No request from the caller subscriber

    # Simple Python program to demonstrate
    # getpass.getpass () to read the password

    import getpass

     

    try :

    p = getpass .getpass ()

    except Exception as error:

    pr int ( 'ERROR' , error)

    else :

      print ( 'Password entered:' , p)

    There is no request from the caller here. Thus, it is set to the default prompt "Password". 
    Output:

     $ python3 getpass_example1.py Password: ('Password entered:', 'aditi') 

    Example 2 : security question
    There are certain programs that ask security questions rather than ask for passwords for added security. Here the hint can be changed to any value.

    # Simple Python program to demonstrate
    # getpass.getpass () to read the security question

    import getpass

     

    p = getpass.getpass (prompt = 'Your favorite flower?' )

     

    if p.lower () = = 'rose' :

      print ( 'Welcome .. !!!' )

    else :

      print ( 'The answer entered by you is incorrect .. !!!' )

    Output:

     $ python3 getpass_example2.py Your favorite flower? Welcome .. !!! $ python3 getpass_example2.py Your favorite flower? The answer entered by you is incorrect .. !!! 
  2. GetUser ()
    GetPass.  getuser ()

    The getuser () function displays the user's login. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME in order and returns the value of the first non-blank line.

    Example 3:

    # Python program to demonstrate how it works
    # getpass.getuser ()

    import getpass

      

    user = getpass.getuser ()

     

    while True :

      pwd = getpass.getpass ( "User Name:% s" % user)

      

    if pwd = = 'abcd' :

    print "Welcome !!!"

    break

    else :

    print "The password you entered is incorrect."

    Exit:

     $ python3 getpass_example3.py User Name: bot Welcome !!! $ python3 getpass_example3.py User Name: bot The password you entered is incorrect. 

This article courtesy of Aditi Gupta . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.





Tutorials