| 1 | #!/usr/bin/python |
| 2 | |
| 3 | import sys, os, termios, hmac, hashlib, getopt, getpass |
| 4 | |
| 5 | def usage(out): |
| 6 | out.write("usage: mkhtpasswd [-h] FILE USERNAME\n") |
| 7 | |
| 8 | opts, args = getopt.getopt(sys.argv[1:], "h") |
| 9 | for o, a in opts: |
| 10 | if o == "-h": |
| 11 | usage(sys.stdout) |
| 12 | sys.exit(0) |
| 13 | if len(args) < 2: |
| 14 | usage(sys.stderr) |
| 15 | sys.exit(1) |
| 16 | |
| 17 | def hashpw(usr, pw): |
| 18 | dig = hmac.new(pw, digestmod=hashlib.sha1) |
| 19 | dig.update(usr) |
| 20 | return dig.hexdigest() |
| 21 | |
| 22 | if ':' in args[1]: |
| 23 | sys.stderr.write("mkhtpasswd: username cannot contain `:'\n") |
| 24 | sys.exit(1) |
| 25 | |
| 26 | passwds = {} |
| 27 | if os.path.exists(args[0]): |
| 28 | with open(args[0]) as fp: |
| 29 | for line in fp: |
| 30 | usr, pw = line.strip().split(':') |
| 31 | passwds[usr] = pw |
| 32 | |
| 33 | passwds[args[1]] = hashpw(args[1], getpass.getpass()) |
| 34 | |
| 35 | with open(args[0], "w") as fp: |
| 36 | for usr, pw in passwds.iteritems(): |
| 37 | fp.write("%s:%s\n" % (usr, pw)) |