theharshest
theharshest

Reputation: 7867

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

Upvotes: 9

Views: 49775

Answers (3)

Abhay Nagar
Abhay Nagar

Reputation: 1

I was also going through the same issue where the read_very_eager() function was not displaying any data. From some post got the idea that the command will require some time to execute. so used the time.sleep() function.

Code Snippet:

tn.write(b"sh ip rou\r\n")
time.sleep(10)
data9 = tn.read_very_eager()
print(data9)

Upvotes: 0

Pythomania
Pythomania

Reputation: 658

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.

Upvotes: 10

Pushpak Dagade
Pushpak Dagade

Reputation: 6450

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

Upvotes: 4

Related Questions