Skip to content

Instantly share code, notes, and snippets.

@braoru
Created October 31, 2014 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braoru/088ff69ea327156c7587 to your computer and use it in GitHub Desktop.
Save braoru/088ff69ea327156c7587 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Transorme user password to cryp(3) compliant line.
Could be usefull to use with useradd -p 'crypt(3) line'
"""
__author__ = "braoru@gmail.com"
__maintainer__ = ""
__version__ = "0.0.1"
import crypt
import random
import getpass
import optparse
import sys
import csv
from string import ascii_letters, digits
#command line parsing
parser = optparse.OptionParser(
"%prog [options]", version="%prog " + __version__
)
parser.add_option(
'-F',
'--input-file',
dest="source_file",
help='file to load'
)
parser.add_option(
'-I',
'--interactive',
dest="is_interactive",
action="store_true",
default=False,
help='Enable interactive mode'
)
def salted_crypt_3(
password,
method_id=6
):
"""
Generate a crpyt(3) compliant line
Keyword arguments:
password -- password to process
method_id -- Method id to use (default is 6)
"""
salt = ''.join(
[
random.choice(
ascii_letters + digits
) for _ in range(16)
]
)
crypt_3_line = crypt.crypt(
password,
'${method}${salt}'.format(
method=str(method_id),
salt=salt
)
)
return crypt_3_line
if __name__ == "__main__":
opts, args = parser.parse_args()
if args:
parser.error("Does not accept any argument.")
if opts.is_interactive:
password = getpass.getpass("password please: ")
print(
salted_crypt_3(
password=password
)
)
sys.exit(2)
if not opts.source_file:
print("Error : If not interfactive you must specify an input file")
sys.exit(2)
#Read the file and generate for each line the hash line
with open(opts.source_file, 'rb') as password_file:
lines = csv.reader(
password_file,
delimiter=','
)
for line in lines:
username = line[0]
shadow = salted_crypt_3(
password=line[1]
)
print(
"{username}:{shadow}".format(
username=username,
shadow=shadow
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment