Search code examples
pythontelnet

Python telnetlib telnet.write() dropping messages


Given the following code:

import telnetlib
import sys
def func1(IP,user,passw):
    t=telnetlib.Telnet(IP)
    t.write(user.encode('ascii')+b'\n')
    t.write(passw.encode('ascii')+b'\n')
    return t

def func2(t,command):
    t.write(command.encode('ascii')+b'\n')
    print(command)

user=sys.argv[1]
passw=sys.argv[2]
IP=sys.argv[3]
t=func1(IP,user,passw)
for i in range(6):
    func2(t, "message "+str(i))

By looking at the server and also Wiresharking it, only messages 1 and 2 gets through.

Now, if I change the func2(t,command) function as follows:

def func2(t,command):
    t.write(command.encode('ascii')+b'\n')
    t.read_eager()   #This is the new line.
    print(command)

It all works fine and all messages are been transmitted.

Any idea?

Python3.3 WindowsXP


Solution

  • You need to read the text coming back to prevent the socket blocking. This is why your other method works.

    In a real world session you would always be reading back the results of logging in and of commands.