1

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.

Grivian
  • 13
  • 3
  • Are you providing the same port in your python script? I see tn = telnetlib.Telnet('xxx.xxx.xxx.xxx', Y) but no port specified – Wesley De Keirsmaeker Nov 10 '17 at 16:20
  • Maybe python is sandboxed somehow and it's not allowed to open sockets? – Yaroslav Surzhikov Nov 10 '17 at 16:22
  • Does this work for you? `import telnetlib; tn = telnetlib.Telnet('bofh.jeffballard.us', 666); print(tn.read_all().decode()); tn.close()` – PM 2Ring Nov 10 '17 at 16:25
  • Y is the port, I edited it so it is more clear. – Grivian Nov 10 '17 at 16:25
  • Yes it works. Output: `=== The BOFH-style Excuse Server --- Feel The Power! === By Jeff Ballard === See http://www.cs.wisc.edu/~ballard/bofh/ for more info. Your excuse is: Write-only-memory subsystem too slow for this machine. Contact your local dealer.` – Grivian Nov 10 '17 at 16:29
  • Excellent. So we know that Python can do telnet to a remote host on your machine. – PM 2Ring Nov 10 '17 at 16:35
  • Now it works with the original code. It appears that restarting the session to the remote host solved the issue. – Grivian Nov 10 '17 at 16:39

1 Answers1

0

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.

Grivian
  • 13
  • 3