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

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

  部分代码:

 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)

 

转载于:https://www.cnblogs.com/Mail-maomao/p/6896693.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值