Search code examples
python-3.xtelnettelnetlib3

Get only output from telnet command


I am using telnetlib3 to access a Telnet server with python. With the following code, I am correctly getting the result, but the output is cluttered by all the input prompts. I would like to get only the clear result of the command show all-outlets-status, without any other line. Is it possibile?

#!/usr/bin/env python3


import asyncio
import telnetlib3

async def shell(reader, writer):
    rules = [
            ('login as:', '.....'),
            ('password:', '......'),
            ('PE-08I-532236$ ', 'show all-outlets-status'),
            ('PE-08I-532236$ ', 'exit'),
            (') >', 'logout'),
            ]

    ruleiter = iter(rules)
    expect, send = next(ruleiter)
    while True:
        outp = await reader.read(1024)
        if not outp:
            break

        if expect in outp:
            writer.write(send)
            writer.write('\r\n')
            try:
                expect, send = next(ruleiter)
            except StopIteration:
                break

        # display all server output
        print(outp, flush=True)

    # EOF


async def main():
    reader, writer = await telnetlib3.open_connection('10.0.0.59', 23, shell=shell)
    await writer.protocol.waiter_closed


if __name__ == '__main__':
    asyncio.run(main())

Solution

  • You can collect all the output and then print it
    Replace your while-loop with this:

    while True:
        outp = await reader.read(1024)
        if not outp:
            break
    
        if expect in outp:
            writer.write(send)
            writer.write('\r\n')
            try:
                expect, send = next(ruleiter)
            except StopIteration:
                break
    
        # Start collecting output after the show command is sent
        if 'show all-outlets-status' in outp:
            collecting_output = True
            continue
        
        # Stop collecting output after the prompt reappears
        if 'PE-08I-532236$ ' in outp and collecting_output:
            collecting_output = False
        
        # Collect the output if we are in the collecting phase
        if collecting_output:
            result.append(outp)
    
    # Print the collected result
    print(''.join(result).strip(), flush=True)