pexpect_1.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pexpect

def connect(ip,passwd,cmd):
    ret = -1
    ssh = pexpect.spawn('ssh root@%s "%s"'%(ip,cmd),timeout=2,searchwindowsize=10)
    try:
        i = ssh.expect(['password: ','continue connecting (yes/no)?'])
	if i == 0:
	    ssh.sendline(passwd)
	elif i == 1:
	    ssh.sendline('yes
')
	    ssh.expect('password: ')
	    ssh.sendline(passwd)

        r = ssh.read()
	print r
        ret = 0
    except pexpect.exceptions.EOF:
	print "EOF"
	ssh.close()
        ret = -1
    except pexpect.TIMEOUT:
	print "TIMEOUT"
	ssh.close()
	ret = -2

    return ret

if __name__ == '__main__':
    iplists = open('iplist','r+')
    iplist = iplists.readlines()
    for ip in iplist:
	templist = []
        ip = ip.strip('
')
        if ip:
            cmd = 'df -h'
            passwdList = [
                {"password":"123"},
                {"password":"1234"},
                {"password":"12345"}
	    ]
            for i in passwdList:
                passwd =  i['password']
		result = connect(ip,passwd,cmd)
		if result == 0:
		    break
                else:
		    templist.append(ip)
		    if templist.count(ip) == 3:
                        with open('errlist','a+') as f:
                            f.write('%s
'%ip)
        else:
            print "Ip error,Please enter right ip info..."

  

原文地址:https://www.cnblogs.com/1qaz/p/9272443.html