使用 pexpect 建立连接

Establishing connection using pexpect

我正在尝试通过以下方法使用 pexpect 建立连接-

child = pexpect.spawn('telnet {console_ip} {console_port}'.format(console_ip=self.obj.get("console_ip"),
                                                                      console_port=int(self.obj.get("console_port"))))
while True:
        index = child.expect(
            ["Hit 'c' key to stop autoboot:", "prompt#", "ARGUS", "Loading:", ".*login:", "Escape character is",
             "Press \[Ctrl+D\] to go to the Suspend Menu", "Please enter your name:"])
        if index == 0:
            child.sendline("ccccc\n")
        elif index == 1:
            time.sleep(1)
            child.sendline("\r run net \r")
            time.sleep(1)
        elif index == 2:
            time.sleep(1)
            child.sendline("\r reset \r")
            time.sleep(5)
        elif index == 3:
            time.sleep(1)
            time.sleep(3)
            break
        elif index == 4:
            child.sendline(user_name+"\r")
        elif index == 5:
            time.sleep(1)
            child.sendline(password+"\r")
        elif index == 6:
            time.sleep(1)
            child.sendline("\r")
        elif index == 7:
            time.sleep(1)
            child.sendline("\r")
        elif index == 8:
            time.sleep(1)
            child.sendline("abcde\r")

我想知道是否有更好的方法可以用更少的代码行实现相同的功能。

减少行数不是当务之急,但尝试提供结构和减少重复可能是当务之急。将提示字符串与其相应的操作更紧密地放在一起会很好。例如,您可以将提示 "Hit 'c' key..." 和发送行字符串回复 "ccccc\n" 配对成一个元组,然后创建所有这些的数组。然后您可能能够删除 if,并在索引元组上调用 sendline 的通用操作。

但是,一旦您开始以这种方式移动,通常最好一路走下去并创建一个简单的 class 来整合提示、回复和操作的其他部分。例如

class match:
    def __init__(self, match, response, before=1, after=0, stop=False):
        self.match = match
        self.response = response
        self.before = before
        self.after = after
        self.stop = stop

    def action(self):
        time.sleep(self.before)
        child.sendline(self.response)
        time.sleep(self.after)
        return self.stop

matches = [
    match("Hit 'c' key to stop autoboot:", "ccccc\n", 0),
    match("prompt#", "\r run net \r", after=1),
    match("ARGUS", "\r reset \r", after=5),
    ... 
]
tomatch = [m.match for m in matches]
while True:
    index = child.expect(tomatch)
    if matches[index].action():
        break