Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

Python telnetlib read output from executing a file

I need to telnet into my device, execute a file, read the output line by line, and then when I get to the prompt, I can continue with my program.

The problem I have is that some of the files I am executing take a very long time to run (some take minutes, others take 3 or 4 hours). Also, the lines themselves may take several seconds to a couple minutes to be output.

There are also a few lines which I don't want to be logged.

The way I figured it out for one of the files was to pass a "last expected line", and then read until the prompt, break, and then move on with the program. The problem is, for most of the files, the last expected line may be different each time.

How do I read until either " " or PROMPT (~ # ), and print each line?

Here is what I have so far:

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}
".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"
", 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 "
" in cmd_out_line:
            cmd_out_line = cmd_out_line.replace("
", "")
        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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...