Skip to content

Instantly share code, notes, and snippets.

@banyek

banyek/hashpw.py

Created Nov 29, 2017
Embed
What would you like to do?
To replace pw to pw hashes in an ansible playbook
#!/usr/bin/env python
"""
This script replaces plain text passwords with sha512 encrypted passwords in
ansbile playbooks - when a lot of users created at once.
There are few known limitations:
- When a line contains the string begins with 'password:' the script will replace the rest
of the line with the hash
- A plain text password shouldn't contain '
- If a password already hashed, the hash will be treated as plain text
Before use pleaase install passlib with:
$ easy_install passlib
"""
import re
import sys
from passlib.hash import sha512_crypt
if len(sys.argv) != 3:
print "Usage: \n\t hashpw infile outfile"
sys.exit(1)
else:
iname = sys.argv[1]
oname = sys.argv[2]
pwre = re.compile('password')
infile = open(iname, "r")
outfile = open(oname, "w")
for line in infile:
token = line.split(":")
if pwre.match(token[0].lstrip()):
plainpw = token[1].rstrip().replace("'","").lstrip()
pwline = token[0] + ":" + " " + "'" + sha512_crypt.encrypt(plainpw) + "'" + "\n"
outfile.writelines(pwline)
else:
outfile.writelines(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment