Search code examples
pythontelnetlib

Python Telnetlib read_until 'a' and 'b' and 'c' and 'd'


When I connect to the telnet session using the telnetlib module, i need to wait for four strings: 'a', 'b', 'c' and 'd' or timeout (10 seconds) before I write a string to the socket.

Is there a way to use tn.read_until('a','b','c','d', timeout)

I just want to wait for all 4 strings to come first before action.

Also these four strings comes in a different order every time. Thanks for any help.


Solution

  • You can use the .expect method to wait for a, b, c or d

    Telnet.expect(list[, timeout])

    Read until one from a list of a regular expressions matches.

    So:

    (index, match, content_including_abcd) = tn.expect(['a', 'b', 'c', 'd'], timeout)
    

    Returns (-1, None, current_buffer) when timeout is reached.


    We could easily change it to a loop to wait for a, b, c and d:

    deadline = time.time() + timeout
    remaining_strings = ['a', 'b', 'c', 'd']
    total_content = ''
    while remaining_strings:
        actual_timeout = deadline - time.time()
        if actual_timeout < 0:
            break
        (index, match, content) = tn.expect(remaining_strings, actual_timeout)
        total_content += content
        if index < 0:
            break
        del remaining_strings[index]