How to copy contents of a text file to a variable over a telnet session using python


I have the following program where I'm redirecting an output on terminal to a text file :

import telnetlib
import time
import string

tn = telnetlib.Telnet("")
print "Attempting Telnet connection...."
tn.read_until("login: ")
tn.read_until("[email protected]:~$")
tn.read_until("[email protected]:/home/root1")
print "Telnet logged in successfully....\n"
tn.write("head /proc/meminfo > /home/a.txt")

I would like to copy the textual contents of this file to a buffer variable and process it. That is, I don't want to read from the console/terminal. I just want to redirect the output to a text file and then read from the text file. Does telnetlib offer any direct function to achieve this or any alternate way to do the same?


EDIT this code reads from a local file on the remote host Please try the following code, which assume that after you execute your command, you get the following string: "[email protected]mypc:/home/root1"

tn.write("cat /home/a.txt")
data = '' 
while data.find("[email protected]:/home/root1") == -1:
    data = tn.read_very_eager()
print data
By : Yaron

TELNET protocol is more or less a distant terminal emulation. It offers no file transfert facilities because other protocols deal with that. That means that once you have written the file on remote system, you will have to display it with cat and store the output of the cat command.

Alternatively you could use a protocol meant for file transfert like FTP, RSYNC, SFTP, FTPS, etc. to download the remote file. Just use the one that is accessible on your remote system.

This video can help you solving your question :)
By: admin