0

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("192.168.1.102")
print "Attempting Telnet connection...."
tn.read_until("login: ")
tn.write("root1\n")
time.sleep(1)
tn.read_until("Password:")
tn.write("\n")
tn.write("\n")
tn.read_until("root1@mypc:~$")
tn.write("su\n")
tn.read_until("root@mypc:/home/root1")
tn.write("\n")
print "Telnet logged in successfully....\n"
tn.write("head /proc/meminfo > /home/a.txt")
tn.write("\n")

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?

skrowten_hermit
  • 437
  • 3
  • 11
  • 28
  • How do you intend to describe the flow in your input text file? You will either have to blindly write a value and then wait for a response from the telnet server (which doesn't match what you have), or you will need a way to describe when to sleep(1), when to send multiple response lines rather than just one line (e.g. after Password: you write two lines), etc. Can you provide a sample of what your input text file will look like, using the above code as a guide for what it will do? – Matt Jordan Mar 22 '16 at 15:46

2 Answers2

2

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.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

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: "root@mypc:/home/root1"

tn.write("cat /home/a.txt")
tn.write("\n")
data = '' 
while data.find("root@mypc:/home/root1") == -1:
    data = tn.read_very_eager()
print data
Yaron
  • 10,166
  • 9
  • 45
  • 65
  • This I am aware of. But, I don't want want to read directly. I want it to read from a text file only. That is, I want to redirect the output to a text file and read from the text file. I'll include this condition to the post as well. – skrowten_hermit Mar 22 '16 at 15:38
  • So, you'd like to ask: how can I read the content of a local file on a remote host (preferred using the telnetlib library)? – Yaron Mar 22 '16 at 15:46