Per Erik Strandberg /cv /kurser /blog

I just discovered the getpass class in Python (see [1]). And again I am falling in love - the saying that Python comes with batteries included is indeed true.

This silly test-program gets a password twice and compares the results, if there is a match the password is printed on screen. If there is a mismatch the user is informed of this (and the passwords are displayed).

Features

GetPass comes with two functions of particular interest: getpass and getuser. By looking a bit under the hood we find more that that (to find out what it means is left as an excercise [:)]-|--< ):

>python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35) 
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import getpass
>>> dir(getpass)
[<snip>, 'default_getpass', 'getpass', 'getuser', <snip>, 'unix_getpass', 'win_getpass']
>>> getpass.unix_getpass()
Password: 
'foo'
>>> getpass.win_getpass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/getpass.py", line 50, in win_getpass
    import msvcrt
ImportError: No module named msvcrt
>>> getpass.default_getpass()
Warning: Problem with getpass. Passwords may be echoed.
Password: foobar
'foobar'

Example of a small program

This little program illustrates the method getpass (that is similar to raw_input but it does not echo the keypunches) and the method getuser (that gets the login name).

import getpass
print "WARNING: do not provide a real password!"
print "%s, enter your " % getpass.getuser(), 
pw1 = getpass.getpass()
print "Confirm ",
pw2 = getpass.getpass()

if pw1 == pw2:
    print 'Your password was "%s".' % pw1
else:
    print 'BAD: you provided different passwords "%s" and "%s".' % (pw1, pw2)

Example of Usage

First we provide the same password twice:

>python get_password.py
WARNING: do not provide a real password!
per, enter your Password: 
Confirm Password: 
Your password was "fnord".

And now we provide different passwords:

>python get_password.py
WARNING: do not provide a real password!
per, enter your Password: 
Confirm Password: 
BAD: you provided different passwords "xyzzy" and "LiBeBCNOFNe".

Conclusions

No more need to pass the password in as a command line argument or implement an ugly hacked version of raw_input - thank god (no: thank Guido!).


This page belongs in Kategori Programmering