#!/usr/bin/python import sys, os, termios, hmac, hashlib, getopt, getpass def usage(out): out.write("usage: mkhtpasswd [-h] FILE USERNAME\n") opts, args = getopt.getopt(sys.argv[1:], "h") for o, a in opts: if o == "-h": usage(sys.stdout) sys.exit(0) if len(args) < 2: usage(sys.stderr) sys.exit(1) def hashpw(usr, pw): dig = hmac.new(pw, digestmod=hashlib.sha1) dig.update(usr) return dig.hexdigest() if ':' in args[1]: sys.stderr.write("mkhtpasswd: username cannot contain `:'\n") sys.exit(1) passwds = {} if os.path.exists(args[0]): with open(args[0]) as fp: for line in fp: usr, pw = line.strip().split(':') passwds[usr] = pw passwds[args[1]] = hashpw(args[1], getpass.getpass()) with open(args[0], "w") as fp: for usr, pw in passwds.iteritems(): fp.write("%s:%s\n" % (usr, pw))