Python telnetlib 从执行文件中读取输出

问题描述

我需要 telnet 到我的设备,执行一个文件,逐行读取输出,然后当我看到提示时,我可以继续我的程序。

我遇到的问题是我正在执行的某些文件需要很长时间才能运行(有些需要几分钟,有些需要 3 或 4 小时)。此外,行本身可能需要几秒钟到几分钟才能输出

还有几行我不想被记录。

我为其中一个文件找到的方法是传递“最后一行”,然后阅读直到出现提示,中断,然后继续执行程序。问题是,对于大多数文件,最后预期的行每次都可能不同。

如何阅读直到 "\n" 或 PROMPT (~ # ),并打印每一行?

这是我目前所拥有的:

def _encode_str(in_str):
    """Encodes a string to a byte string"""
    return bytes(in_str,encoding=ENCODING)

def _decode_byte_str(byte_str):
    """Decodes a byte string"""
    return byte_str.decode(ENCODING)

def _tel_write_cmd(session,cmd_str):
    """Performs a command in a session"""
    bcmd_str = _encode_str(cmd_str)
    session.write(bcmd_str)

def _tel_read_loop(session,ip,cmd_str,skip_line,cmd_last_line,timeout):
    """Returns output from a command line-by-line"""
    count = 0
    cmd_str = "{0}\r\n".format(cmd_str)
    cmd_str_len = len(cmd_str)
    _tel_write_cmd(session,cmd_str)
    while True:
        count += 1
        cmd_out_line = session.read_until(b"\n",timeout)
        if count == 1:
            cmd_out_line = cmd_out_line[cmd_str_len:PROMPT_LEN] # Trim output to only return command's returned output
        cmd_out_line = _decode_byte_str(cmd_out_line) # Decode to a str
        if "\r" in cmd_out_line:
            cmd_out_line = cmd_out_line.replace("\r","")
        if skip_line is None:
            logging.debug("[{0}] - {1}".format(ip,cmd_out_line).strip())
        elif skip_line not in cmd_out_line:
            logging.debug("[{0}] - {1}".format(ip,cmd_out_line).strip())
        if cmd_last_line in cmd_out_line:
            session.read_until(PROMPT)
            break

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)