import telnetlib
import socket
import logging
import errno


def connect_telnet(router, port):
    """
    Establish a telnet connection to a router on a given port
    """
    #
    # Establish a telnet connection to the router
    try:
        # Init telnet
        telnet_conn = telnetlib.Telnet(router, port, 3)
        # Connection established
        return telnet_conn
    except socket.timeout:
        # Timeout expired
        logging.error('Error: cannot establish a connection '
                      'to %s on port %s\n', str(router), str(port))
    except socket.error as err:
        # Socket error
        if err.errno != errno.EINTR:
            logging.error('Error: cannot establish a connection '
                          'to %s on port %s\n', str(router), str(port))
    return None