Speaking telnet better

May 04, 2017 · By Preston Rohner · PythonDeviceManagement

Speaking telnet better – 10 minutes

In our last iteration of the program we introduced the TelnetHost class. However, the class didn’t really fully implement Telnet communications. It just executed a quick command to make sure that things work. Let’s make that bad boy do some real work now.

We add a new method to the TelnetHost class. It’s called get_command_results(). In this initial version of this method we are going to take a new approach to sending commands to the host.

def get_command_results(self):
    interval = 0.1
    maxseconds = 10

    start = datetime.now()
    start_secs = time.mktime(start.timetuple())
    output = ''
    while True:
        time.sleep(interval)
        output += self.telnet.read_very_eager().decode('ascii')
        output = output.rstrip()

        now = datetime.now()
        now_secs = time.mktime(now.timetuple())
        et_secs = now_secs - start_secs
        if et_secs > maxseconds:
            break

        if len(output) > 0 and (output[-1] == '#' or output[-1] == '>'):  ## got a Cisco command prompt
            break

    return output

This implementation drops into a could-accidentally-become-infinite while loop. The loop keeps rolling around and checking whether the output variable ends with # or ends with > (either of those would indicate the host has returned to a command prompt).

The method also has some safety built into it. Before the loop begins we record the number of seconds since January 1, 1970 into start_secs. Each time we loop we save the current number of seconds since 1/1/1970 into now_secs. If the difference between start_secs and now_secs exceeds our maxseconds then we know we’ve been in our loop too long.