Search code examples
pythonexpecttelnetremote-servertelnetlib

Unable to telnet to remote host using pythons telnetlib, although bash telnet <host> <port> works


I am using pythons telnetlib as an alternative to the expect shell in unix in order to automate a telnet session. I have tried expect and it works fine, but I want to use the features from python. A normal "telnet HOST PORT" works fine. The following simple code yields an exception:

import telnetlib
tn = telnetlib.Telnet('xxx.xxx.xxx.xxx', PORT)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/telnetlib.py", line 209, in __init__
    self.open(host, port, timeout)
  File "/usr/lib64/python2.7/telnetlib.py", line 225, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "/usr/lib64/python2.7/socket.py", line 571, in create_connection
    raise err
socket.error: [Errno 101] Network is unreachable

I am running this from a remote host, a redhat linux distribution. I have also tried to create a connection using socket.connect() and get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 101] Network is unreachable

telnetlib works if I want to connect to localhost, but only to localhost. I have tried other telnet servers also and I get the same "Network is unreachable" error.

I am also aware that pexpect exist, but I would prefer to use telnetlib if possible.


Solution

  • It works now. The solution was simple, terminate and restart the session to the remote host where I was running the script. The reason why it didn't work before still escapes me, however there has been issues with NX, which I use to access the host, in the past.