1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Python 远程批量修改密码脚本
#tar -zxvf pexpect-3.0.tar.gz
#cd pexpect-3.0
#python setup.py install
#!/usr/bin/env python
#coding:utf8
import  pexpect                            
import  sys 
iplist  =  [ '192.168.140.142' , '192.168.140.145' ##定义主机列表
oldpasswd  =  '234567'  ##旧密码
newpasswd  =  '1234567'  ##新密码
while  iplist:
     ip  =  iplist[ - 1 ##获取一个IP
     iplist.pop()  ##列表去掉一个值
     child  =  pexpect.spawn( 'ssh root@' + ip)  ##定义触发
     fout  =  file ( 'passlog.txt' , 'a' ##定义日志文件,
     child.logfile  =  fout
     try :
         while  True :
             index  =  child.expect([ '(yes/no)' , '(?i)password:' ])
             if  index  = =  0 :
                 child.sendline( 'yes' )
             elif  index  = =  1 :
                 child.sendline(oldpasswd)
                 child.expect( '#' )
                 child.sendline( 'echo  ' + newpasswd + ' | passwd --stdin root' )
                 child.expect( '#' )
                 child.sendline( 'exit' )
     except  pexpect.TIMEOUT:
         print  >>sys.stderr, ip + ' timeout'
     except  pexpect.EOF:
         print  >>sys.stderr, ip + ' <the end>'
1 )spawn类
  class  pexpect.spawn(command,args = [],timeout = 30 ,maxread = 2000 ,searchwidowsize = None
,logfile = None ,cwd = None ,env = None ,ignore_sighup = True )
2 )run函数
pexpect.run(command,timeout = - 1 ,withexitstatus = False ,events = None ,extra_args = None ,
logfile = None ,cwd = None ,env = None ).
3 )pxssh类
class  pexpect.pxssh.pxssh(timeout = 30 ,maxread = 2000 ,searchwidowsize = None ,logfile = None ,
cwd = None ,env = None )
pxssh常用的三个方法:
     login()建立连接;
     logout()断开连接;
     prompt()等待系统提示符,用于等待命令执行结束
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/python# encoding=utf-8# Filename: pexpect_test.pyimport pexpectdef sshCmd(ip, passwd, cmd):
     ret  =  - 1
     ssh  =  pexpect.spawn( 'ssh root@%s "%s"'  %  (ip, cmd))     try :
         =  ssh.expect([ 'password:' 'continue connecting(yes/no)?' ], timeout = 5 )         if  = =  0 :
             ssh.sendline(passwd)         elif  = =  1 :
             ssh.sendline( 'yes\n' )
             ssh.expect( 'password:' )
             ssh.sendline(passwd)
         ssh.sendline(cmd)
         =  ssh.read()         print  r
         ret  =  0
     except  pexpect.EOF:         print  "EOF"
         ret  =  - 1
     except  pexpect.TIMEOUT:         print  "TIMEOUT"
         ret  =  - 2
     finally :
         ssh.close()     return  ret
 
sshCmd( 'xxx.xxx.xxx.xxx' , 'xxxxxx' , 'ls /root' )

本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1827747,如需转载请自行联系原作者