[Tutor] How to save telnet output logs to a text file in python
Steven D'Aprano
steve at pearwood.info
Thu Feb 26 13:03:20 CET 2015
On Thu, Feb 26, 2015 at 12:24:17PM +0530, kailash ganesh wrote:
> Hi All,
>
> Please someone help on the below request.
>
> I am learning python and trying to connect my satellite decoder using
> telnet. When I tried to connect my device through telnet python script, I
> could successfully connected to the device.
Can you show the code you use?
You have something below which looks like code, but it doesn't seem to
be Python. It has line numbers. Can you explain what it is please?
> But i want to capture/save as well as read the output and logs of device
> (connected thru telnet) from starting in a text file. Also, i want to send
> few commands to get the output of the command and store in the text file.
The documentation for the telnetlib module includes this example:
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write(b'guido\r\n')
>>> print(tn.read_all())
Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
I tried running that example, but www.python.org doesn't respond for me
and I eventually got this error:
TimeoutError: [Errno 110] Connection timed out
Maybe my firewall blocks that port, or maybe the site is not listening.
But the important part is the tn.read_all() function. If that works for
you, you can do this instead:
output = tn.read_all()
# display to screen
print(output)
# write to a file
with open("MyFile.txt", "wb") as f:
f.write(output)
# Check that the file wrote correctly.
with open("MyFile.txt", "rb") as f:
print(f.read())
Does that help?
If you need more help, please show your code, without line numbers, and
show any errors you get.
--
Steve
More information about the Tutor
mailing list