python pexpect包用法

简介

  Pexpect 是 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Python 模块。因为工作需要我用它来抓取交换机相关数据信息,话不多说,附上我的代码片段、说明。

代码:

def connect(user, host, password):
    ssh_newkey = "Are you sure you want to continue connecting"
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)  # 实例化连接
    ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:', pexpect.EOF])  ##预期捕获的结果,只有遇到password才是能够继续往下走的,其他预期都是代表无法正常登录
    if ret == 0:  # 捕获超时
        print('[-] Error Connecting timeout:' + str(host))
        logger.warning("Error Connecting: timeout" + str(host))
        return
    if ret == 1:  # 捕获了ssh_newkey的消息,需要互动
        child.sendline('yes')  # 发送yes
        ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:', pexpect.EOF])
        if ret == 0:
            print('[-] Error Connecting timeout:' + str(host))
            logger.warning("Error Connecting: timeout" + str(host))
            return
    if ret == 3: # 捕获不知名的错误
        print('[-] Error Connecting eof:' + str(host))
        logger.warning("Error Connecting eof:" + str(host))
        return
    child.sendline(password)
    r = child.expect(['>','Permission denied',pexpect.TIMEOUT,pexpect.EOF])  # 捕获命令提示符,因为我们交换机上的tooltip都是以">"结尾的
    if r > 0:
        print('[-] Permission denied:' + str(host))
        logger.warning("Permission denied:" + str(host))
        return
    return child

  

#将系统ansi字符替换为空,以避免后续匹配失败问题
def escape_ansi(line):
    ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
    return ansi_escape.sub('', line)

#执行命令
def send_command(child, cmd):
    patterns = ['---- More ----','>', pexpect.EOF,pexpect.TIMEOUT]
    data = ''
    child.sendline(cmd)
    #遇到需要翻页的情况,需要输入空格键,进行翻页
    while True:
        ret = child.expect(patterns)
        data += escape_ansi(child.before.decode())
        if ret == 0:
            child.send(' ')
        elif ret >= 1:
            break
    return data

  

  

posted @ 2019-09-27 17:15  golden23  阅读(686)  评论(0编辑  收藏  举报