htpasswd with Python

As many Apache users know, the htpasswd1 is used to create a file with username/password pairs. The format for the file is simply a username, colon, encrypted password. For example:

foo:oNAU4bgeqQHt2

The username is foo and the password is bar encrypted with a salt of oN2

Now, there are good reason why an admin might not want to install apache in order to get htpasswd, yet still need to create a password file. Since there isn't a good reason against having Python installed, we can simply use that to create the file.

The encryption used by htpasswd is the basic UNIX crypt(3) function. Python provides a very nice interface to this function3.

import crypt
print crypt.crypt('bar', 'oN')

This will print bar, encrypted with a salt of oN4

Obviously, the above code isn't incredibly complex. So below is a bit of code that might be a little more useful.

# Script should be passed two paramters
# username and password
import crypt
import sys
if len(sys.argv) == 3:
    print("%s:%s" % (sys.argv[1], crypt.crypt(sys.argv[2], sys.argv[2])))

To use the code, save it as htpasswd.py or something and then simply pass it two parameters, username then password, and redirect the output into a file. For example:

python htpasswd.py foo bar > passwd_file

There are obvious deficits in the above code, such as minimal input verification, and seeding the encryption with the first two letters of the password. However, I think it illustrates the idea and I encourage someone else to improve it.

And improve it they have. There is now a much better script in http://trac.edgewall.org/browser/trunk/contrib/htpasswd.py


  1. 1. if using Apache 2.x and depending on distribution, it may be called htpassw2
  2. 2. apparently chosen at random by htpasswd2
  3. 3. for obvious reasons, this only works on *NIX systems
  4. 4. The salt is any two characters in the set: [a-zA-Z0-9./]

  • Posted: 2007-11-28 00:09 (Updated: 2008-03-05 05:56)
  • Author: pacopablo
  • Categories: (none)

Comments

No comments.