【问题标题】:Establishing connection using pexpect使用 pexpect 建立连接
【发布时间】:2020-05-07 09:01:41
【问题描述】:

我正在尝试通过以下方法使用 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")

我想知道是否有更好的方法可以用更少的代码来实现。

【问题讨论】:

    标签: python pexpect remote-connection


    【解决方案1】:

    减少行数不应该是必须的,但尝试提供结构并减少重复可能是必要的。最好让提示字符串及其相应的操作更紧密地结合在一起。例如,您可以将提示“Hit 'c' key...”配对成一个元组,发送线字符串回复“ccccc\n”,然后创建一个包含所有这些的数组。然后,您可能能够删除 if 并在索引元组上调用 sendline 的通用操作。

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2019-11-20
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多