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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With