Лучший способ установить sh соединение с помощью pexpect - PullRequest
2 голосов
/ 07 мая 2020

Я пытаюсь установить sh соединение с помощью 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")

Я хочу знать, есть ли лучший способ реализовать то же самое с меньшим количеством строк кода.

1 Ответ

1 голос
/ 07 мая 2020

Уменьшение количества строк не должно быть императивом, но попытка обеспечить структуру и уменьшить повторение может быть. Было бы неплохо, если бы строка приглашения и соответствующее ей действие были ближе друг к другу. Вы можете, например, объединить в кортеж приглашение «Hit 'c' key ...» и строковый ответ в строке отправки «ccccc \ n», а затем создать массив из всего этого. После этого вы сможете удалить if и получить общее действие, вызывающее линию отправки в индексированном кортеже.

Но как только вы начнете двигаться таким образом, часто лучше всего go полностью и создать простой класс для объединения подсказки, ответа и других частей действия. Например,

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
...