Last Updated: February 25, 2016
·
7.921K
· darthlukan

Read STDOUT from Telnet Terminal in Python

Here's a little Python recipe that I use whenever I have to deal with getting the stdout from a telnet terminal (more often than you'd think!).

The code (Python):

import telnetlib


class TelnetWorkers(object):
    """
    Creates our connection, holds and handles data.
    """

    def __init__(self, IP, PORT):
        # IP and PORT are strings
        self.connection = telnetlib.Telnet(IP, PORT)
        self.data = []

    def getMoreData(self):
        """
        Reads STDOUT, splits on and strips '\r\n'.

        Returns list.
        """
        # 10 means that we're going to timeout after 10 seconds if
        # we don't get any input that satisfies our regex.
        cursor = self.connection.read_until('\r\n', 10)

        # Make sure we have something to work with.
        if len(cursor) > 0:
            for line in cursor.split(','):
                # Sometimes we get empty strings on split.
                if line != '':
                    self.data.append(line)
        return self.data

 ... Add your specific methods here ...

This is useful if you're receiving data, such as from shipping lanes (AIS data), to a telnet server and want to use that data in some way (decoding for message/position display).