Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading output with telnetlib in realtime

I'm using Python's telnetlib to telnet to some machine and executing few commands and I want to get the output of these commands.

So, what the current scenario is -

tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("command1")
tn.write("command2")
tn.write("command3")
tn.write("command4")
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op
#here I get the whole output

Now, I can get all the consolidated output in sess_op.

But, what I want is to get the output of command1 immediately after its execution and before the execution of command2 as if I'm working in the shell of the other machine, as shown here -

tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("command1")
#here I want to get the output for command1
tn.write("command2")
#here I want to get the output for command2
tn.write("command3")
tn.write("command4")
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op
like image 909
theharshest Avatar asked Apr 12 '12 14:04

theharshest


2 Answers

I ran into something similar while working with telnetlib.

Then I realized a missing carriage return and a new line at the end of each command and did a read_eager for all commands. Something like this:

 tn = telnetlib.Telnet(HOST, PORT)
 tn.read_until("login: ")
 tn.write(user + "\r\n")
 tn.read_until("password: ")
 tn.write(password + "\r\n")

 tn.write("command1\r\n")
 ret1 = tn.read_eager()
 print ret1 #or use however you want
 tn.write("command2\r\n")
 print tn.read_eager()
 ... and so on

instead of only writing the command like:

 tn.write("command1")
 print tn.read_eager()

If it worked with just a "\n" for you, adding only a "\n" might be enough instead of "\r\n" but in my case, I had to use "\r\n" and I haven't tried with just a new line yet.

like image 137
Pythomania Avatar answered Oct 21 '22 23:10

Pythomania


You must refer to the documentation of telnetlib module here.
Try this -

tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("command1")
print tn.read_eager()
tn.write("command2")
print tn.read_eager()
tn.write("command3")
print tn.read_eager()
tn.write("command4")
print tn.read_eager()
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op
like image 28
Pushpak Dagade Avatar answered Oct 21 '22 23:10

Pushpak Dagade