turn off py2 builds, that worked all right with all the tags
[infrastructure.git] / scripts / trash / matching_passwds.py
1 #!/usr/bin/env python
2
3 ####################
4 __doc__="""\
5 This script expects a mandatory plain passwd, 
6 and an optional MD5-encoded passwd
7
8 If both are provided, we check that they match
9 Otherwise we return an encrypted passwd 
10 """
11
12 __author__="Thierry Parmentelat, INRIA Sophia Antipolis"
13
14 ####################
15 import getopt
16 import sys
17 import re
18
19 from crypt import crypt
20 import random
21 import string
22     
23 #################### md5 passwds syntax
24 magic='$1$'
25 re_magic='\$1\$'  # $ needs \ in regular expression
26
27 ####################
28 def usage():
29    print "Usage: %s plain [encrypted]"%sys.argv[0]
30    print __doc__
31
32 ####################
33 ####################
34 def getsalt(chars = string.letters + string.digits):
35     # generate a random 8-character 'salt'
36     return (random.choice(chars)
37             + random.choice(chars)
38             + random.choice(chars)
39             + random.choice(chars)
40             + random.choice(chars)
41             + random.choice(chars)
42             + random.choice(chars)
43             + random.choice(chars))
44
45 ##########
46 # returns a string
47 def compute_encrypted (plain):
48    return crypt(plain,magic+getsalt()+'$')
49
50 ####################
51 ####################
52 # returns a boolean
53 def check_encrypted (plain,passwd):
54    
55    no_dollar="[^\$]+"
56    re_passwd=(re_magic
57               +"(%s)"%no_dollar
58               +'\$'
59               + "(%s)"%no_dollar)
60 #   print "in="+passwd
61 #   print "re="+re_passwd
62    m_passwd=re.compile(re_passwd)
63    r=m_passwd.match(passwd)
64
65    if not r:
66       print 'passwd wrong syntax %s'%passwd
67       ok= False
68    else:
69       salt=r.group(1)
70       checked=crypt(plain,magic+salt+'$')
71       ok = (checked==passwd)
72    return ok
73
74 ####################
75 def main ():
76
77    (opts, argv) = getopt.getopt(sys.argv[1:], "h")
78    for (opt, optval) in opts:
79       if opt == '-h':
80          usage()
81          return 1
82
83    args=len(argv)
84    if args==1:
85       [plain]=argv
86       try:
87          encrypted=compute_encrypted(plain)
88          print encrypted
89          return 0
90       except:
91          return 1
92    elif args==2:
93       [plain,passwd]=argv
94       try:
95          ok = check_encrypted (plain,passwd)
96          if ok:
97             return 0
98          else:
99             return 1
100       except:
101           return 1
102    else:
103        usage()
104        return 1
105    print "END should not occur"
106          
107 ####################
108 if __name__ == '__main__':
109    sys.exit(main())
110
111
112