Skip to content

Instantly share code, notes, and snippets.

@rpip
Last active August 29, 2015 14:09
Show Gist options
  • Save rpip/ffd83b88e1d933992bc0 to your computer and use it in GitHub Desktop.
Save rpip/ffd83b88e1d933992bc0 to your computer and use it in GitHub Desktop.
Generate passwords for KeePass database. Output: (password, hash)
#!/usr/bin/env python
# USAGE: ./bin/passwd $password_prefix $dbpath $inventory_hostname -w
import sys, os
import string
import random
from datetime import datetime
from keepass import kpdb
from passlib.hash import sha256_crypt
DB_FILE = "%s_passwords.kpdb" % datetime.now().strftime("%Y_%m_%d_%H_%M")
DB_READ_INDEX = 2
DB_PASSWORD = PASSWORD_PREFIX = "c0ns0le!"
def get_db(db_path=DB_FILE, db_password=DB_PASSWORD):
"Returns a connection to the KeePass DB"
if not os.path.exists(db_path):
kpdb_h = kpdb.Database()
kpdb_h.write(db_path, db_password)
else:
kpdb_h = kpdb.Database(db_path, db_password)
# return db
return kpdb_h
def id_gen(id_prefix='', size=5, chars=string.ascii_uppercase + string.digits):
"generate unique ID"
rand_str = ''.join(random.choice(chars) for _ in range(size))
# hash the generated id
uniq_passwd = id_prefix + rand_str
return (uniq_passwd, sha256_crypt.encrypt(uniq_passwd))
if __name__ == '__main__':
prefix = sys.argv[1] if len(sys.argv) >= 6 else PASSWORD_PREFIX
(password, hash_passwd) = id_gen(prefix)
if '-w' in sys.argv:
db_fname = sys.argv[2]
db = get_db(db_fname)
inventory_hostname = sys.argv[3]
db.add_entry(path="servers",
title=inventory_hostname,
username="root",
password=password,
url=inventory_hostname,
notes=hash_passwd
)
db.write(db_fname, DB_PASSWORD)
# print generated password and hash
print "%s => %s" % (password, hash_passwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment