系统动态密码(1分钟生成一次)

 1 # sys
 2 import os
 3 from datetime import datetime
 4 from string import maketrans, lowercase
 5 from hashlib import md5
 6 # thirdparty
 7 #self program
 8 
 9 BASIC_PASSWD = ''
10 USER_PATH = '/etc/passwd'
11 SKIP_USERS = ['root']         #忽略影响账号
12 
13 '''
14     gen a password
15 '''
16 def _get_current_min_time():
17     return datetime.now().strftime("%Y-%m-%d %H:%M")
18 
19 def _get_offset():
20     now = datetime.now().strftime("%m%d")
21     return sum([int(i) for i in now])
22 
23 def _gen_offset_map():
24     offset = _get_offset()
25     return maketrans(lowercase,   lowercase[offset:] + lowercase[:offset])
26 
27 def _get_offset_name(name):
28     return name.lower().translate(_gen_offset_map())
29 
30 def _get_orig_txt(name):
31     return _get_current_min_time() + _get_offset_name(name)
32 
33 def gen_password(name):
34     return md5(_get_orig_txt(name)).hexdigest()[-6:]
35 
36 
37 '''
38     change password
39 '''
40 def get_users():
41     try:
42         fn = open(USER_PATH).readlines()
43         users = [user.split(':')[0].strip() for user in fn if len(user.split(':')) >= 7 and user.split(':')[-1].strip().endswith('sh')]
44     except Exception as e:
45         fn = open('/tmp/error_log', 'a')
46         fn.write(str(e))
47         fn.close()
48         users = []
49     return users
50 
51 def _change_passwd(user, passwd):
52     if not user or not passwd:
53         return
54     cmd = 'echo "%s:%s"  | chpasswd 2>/dev/null' % (user, passwd)
55     res = os.popen(cmd).read()
56     if len(res) != 0:
57         fn = open('/tmp/error_log', 'a')
58         fn.write("time:%s\nchange password error:\norig cmd: %s\n\n" % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), cmd))
59         fn.close()
60 
61 def change_password():
62     # fn = open('/tmp/passwd.log', 'a')
63     for user in get_users():
64         if user in SKIP_USERS:
65             continue
66         passwd = gen_password(user)
67         # fn.write("%s %s: %s\n" % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), user, passwd))
68         passwd = BASIC_PASSWD + passwd
69         _change_passwd(user, passwd)
70         # print 'echo "%s:%s"  | chpasswd' % (user, passwd)
71 
72     # fn.close()
73 
74 
75 if __name__ == '__main__':
76     change_password()    

 

posted @ 2015-02-12 14:34  池偏一  阅读(648)  评论(0编辑  收藏  举报