python pexpect

2023-01-31 02:01:11 python pexpect
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()等待系统提示符,用于等待命令执行结束
#!/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:
        i = ssh.expect(['password:', 'continue connecting(yes/no)?'], timeout=5)        if i == 0:
            ssh.sendline(passwd)        elif i == 1:
            ssh.sendline('yes\n')
            ssh.expect('password:')
            ssh.sendline(passwd)
        ssh.sendline(cmd)
        r = 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')


相关文章