算是一個實用的例子,定制系統任務,並將隨機密碼上傳至日志服務器,實現定期修改密碼;
部分代碼:
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)
