check for existance of configuration file.
[stack/cam.git] / lib / utils.py
1
2 __all__ = [
3     'getcertdate', 'fingerprint', 'expired',
4     'cfg2dict', 'mkdir', 'template',
5     'dictmerge', 'd2get', 
6     'openssl'
7     ]
8
9
10 import commands
11 import os, re
12 import time
13
14
15 def getcertdate(crt_file):
16     if os.path.exists(crt_file):
17         o = commands.getoutput('openssl x509 -in %s -noout -dates' % crt_file)
18         m = re.search(r'notAfter=(.*)', o)
19         if m:
20             return time.mktime(time.strptime(m.group(1), 
21                                              '%b %d %H:%M:%S %Y %Z'))
22     return 0
23
24 def expired(crtdate):
25     if crtdate < time.time():
26         return 1
27     else:
28         return 0
29
30 def fingerprint(hash, crt_file):
31     if os.path.exists(crt_file):
32         o = commands.getoutput('openssl x509 -in %s -noout -fingerprint -%s' % (crt_file, hash))
33         m = re.search(r'=(.*)$', o)
34         if m:
35             return m.group(1)
36     return 'NOT FOUND'
37
38 def cfg2dict(cfg, section):
39     d = dict()
40     for k, v in cfg.items(section):
41         d[k] = v
42     return d
43
44 def mkdir(p):
45     try:
46         os.mkdir(p, 0755)
47         print 'created directory \'%s\'' % p
48     except OSError:
49         pass
50
51 def template(file, t, args):
52     f = open(file, 'w')
53     f.write(t % args)
54     f.close()
55
56 def dictmerge(d1, d2):
57     out = dict()
58     for d in [ d2, d1 ]:
59         for k, v in d.items():
60             out[k] = v
61     return out
62
63 def d2get(d1, d2, k, default=None):
64     return d1.get(k, d2.get(k, default))
65
66 def openssl(*args):
67     cmd = "openssl " + ' '.join(["'%s'" % x for x in args])
68     print 'executing "%s"' % cmd
69     return os.system(cmd)
70
71
72