Python实现自动更改系统用户密码,生成随机密码

时间:2022-09-09 16:02:44

  算是一个实用的例子,定制系统任务,并将随机密码上传至日志服务器,实现定期修改密码; 

  部分代码:

 1 #!/usr/bin/env python
2 #coding:utf-8
3 import random,string,os,pexpect,time,re
4 def passwd_Create(): #生成随机密码
5 all_choice = string.ascii_letters+string.digits
6 passwd = ''
7 for i in range(8):
8 passwd += random.choice(all_choice)
9 return passwd
10
11 def passwd_Change(name,pwd): #更改密码
12 child = pexpect.spawn('passwd '+name)
13 index = child.expect(['New password',pexpect.EOF,pexpect.TIMEOUT])
14 if index == 0 :
15 child.sendline(pwd)
16 time.sleep(2)
17 child.sendline(pwd)
18 time.sleep(2)
19 child.close(force=True)
20 else:
21 print "expect ERROR"
22 child.close(force=True)
23
24 def log_Note(name,key): #记录日志
25 with open('/var/log/passwd','a+') as log:
26 counts = time.ctime()+" ["+name+"]"+" password is"+" ["+key+"]"+"\n"
27 log.write(counts)
28
29 def checkPw(passwd): #检测密码的强度
30 plen = len(passwd)
31 print plen
32 chpw1 = re.compile(r'.*[A-Z]+.*')
33 chpw2 = re.compile(r'.*[a-z]+.*')
34 chpw3 = re.compile(r'.*\d{1,}.*')
35 chresult1 = chpw1.findall(passwd)
36 print "匹配大写字符: ",chresult1
37 chresult2 = chpw2.findall(passwd)
38 print "小写字符: ",chresult2
39 chresult3 = chpw3.findall(passwd)
40 print "至少一个数字: ",chresult3
41
42 if chresult1 and chresult2 and chresult3:
43 print "You will change passwd use this password"
44 return 0
45 else:
46 print "password is not safety,will generate a safety passwd"
47 return 1
48
49 users = ['root','tom','alice'] #系统用户列表
50
51 if __name__ == "__main__":
52 for i in range(len(users)):
53 a = 1
54 while a != 0 :
55 keys = passwd_Create()
56 a = checkPw(keys)
57 passwd_Change(users[i],keys)
58 log_Note(users[i],keys)