I am trying to open a telnet connection, write one string, then print everything from the telnet server in Python. I assume I am missing something obvious because the documentation seems pretty self-explanatory and doing what I think is the exact same thing in terminal works fine.
Here is the Python code:
import telnetlib
telnet = telnetlib.Telnet()
telnet.open('192.168.1.128', 9801, 10)
telnet.write("SYSTEM_CAL")
print(telnet.read_all())
This times out after 10 seconds / doesn't successfully connect to the server I assume. Here is the output:
Traceback (most recent call last):
File "/Volumes/Work/Scripting/Telnet Test/main.py", line 9, in <module>
print(telnet.read_all())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/telnetlib.py", line 385, in read_all
self.fill_rawq()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/telnetlib.py", line 576, in fill_rawq
buf = self.sock.recv(50)
socket.timeout: timed out
In the image below I connect to the same server in terminal and everything works fine. At the end I give the "DISCONNECT" command taken by the server which is why the connection closes.
Am I missing something? Why is this working in Terminal and not in Python?
I suppose you are sending your command too early, and the receiving end is ignoring it. Try to read the banner first:
print(telnet.read_until("Welcome."))
telnet.write("SYSTEM_CAL")
print(telnet.read_all())
EDIT:
I also note that you don't have a line-terminating sequence at the end of "SYSTEM_CAL". I presume that, in the interactive session, you press ↵ ENTER after you type "SYSTEM_CAL". If that is the case, you'll need to add \n
at the end of the write()
call:
telnet.write("SYSTEM_CAL\n")
Depending upon other factors outside of your question, it is possible that you may need one of the following instead:
telnet.write("SYSTEM_CAL\r")
telnet.write("SYSTEM_CAL\r\n")