学习使用 python 通过 SSH 连接到交换机

Learning to use python to SSH into switches

我正在学习 pexpect 和正则表达式。 我有两个问题: 1. child.expect(some text here) 实际上必须是正则表达式吗? 2. 如果有人能告诉我为什么我的脚本在输入密码时挂起,将不胜感激。

import pexpect
import getpass
import sys

try:
    switch = raw_input("Host: ")
    un = raw_input("Username: ")
    pw = getpass.getpass("Password: ")

    child = pexpect.spawn("ssh %s@%s" % (un, switch))
    child.logfile = sys.stdout

    selection = child.expect(['Are you sure you want to continue connecting (yes/no)?','login as:'])

    if selection == 0:
        child.sendline("yes")

    elif selection == 1:
        i = child.expect(['login as:','user@10.0.0.65\'s password:'])
        if i == 0:
            child.sendline(un)
        elif i == 1:
            child.sendline(pw)

    child.expect('Switch#')
    child.sendline("show cdp nei")

except Exception as e:
    print("Failed on login")
    print(e)

来自the docs

… The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. …

因此,如果您传递这样的模式:

['Are you sure you want to continue connecting (yes/no)?','login as:']

…这是一个包含两个字符串的列表,它们都将被编译为正则表达式。因此,例如,您将有一个包含单个值 yes/no 的捕获组,出现 0 次或 1 次,这可能不是很有用。

如果您想将它们作为文字字符串进行匹配,最简单的做法可能是对它们调用 re.escape

[re.escape('Are you sure you want to continue connecting (yes/no)?'),
 re.escape('login as:')]