Don't overwrite C:\Unattend.xml in the windows
[snf-image] / snf-image-helper / snf-passtohash.py
1 #!/usr/bin/env python
2
3 # Copyright (C) 2011 GRNET S.A. 
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 # 02110-1301, USA.
19
20 """Generate a hash from a given password
21
22 This program takes a password as an argument and
23 returns to standard output a hash followed by a newline.
24 To do this, it generates a random salt internally.
25
26 """
27
28 import sys
29 import crypt 
30
31 from string import ascii_letters, digits
32 from random import choice
33 from os.path import basename
34 from optparse import OptionParser
35
36
37 # This dictionary maps the hashing algorithm method
38 # with its <ID> as documented in:
39 # http://www.akkadia.org/drepper/SHA-crypt.txt
40 HASH_ID_FROM_METHOD = {
41     'md5': '1',
42     'blowfish': '2a',
43     'sun-md5': 'md5',
44     'sha256': '5',
45     'sha512': '6'
46 }
47
48 def random_salt(length=8):
49     pool = ascii_letters + digits + "/" + "."
50     return ''.join(choice(pool) for i in range(length))
51
52
53 def parse_arguments(input_args):
54     usage = "usage: %prog [-h] [-m encrypt-method] <password>"
55     parser = OptionParser(usage=usage)
56     parser.add_option("-m", "--encrypt-method",
57                         dest="encrypt_method",
58                         type='choice',
59                         default="sha512",
60                         choices=HASH_ID_FROM_METHOD.keys(),
61                         help="encrypt password with ENCRYPT_METHOD [%default] \
62                         (supported: " + ", ".join(HASH_ID_FROM_METHOD.keys()) +")",
63     )
64
65     (opts, args) = parser.parse_args(input_args)
66
67     if len(args) != 1:
68         parser.error('password is missing')
69
70     return (args[0], opts.encrypt_method)
71
72
73 def main():
74     (password, method) = parse_arguments(sys.argv[1:])
75     salt = random_salt()
76     hash = crypt.crypt(password, "$"+HASH_ID_FROM_METHOD[method]+"$"+salt)
77     sys.stdout.write("%s\n" % (hash))
78     return 0
79
80 if __name__ == "__main__":
81         sys.exit(main())
82
83 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :