Bennet Leff
Bennet Leff

Reputation: 374

Python telnetlib read functions return more data than expected

I'm working on a telnet client for an IBM as400 box and have run into some trouble getting the right amount of data returned. Initially, the program should connect to a telnet session which has a username and password field which it writes to, then go to the user shell which lets employees input data, access a database, etc. When I call read_very_eager it returns the buffer filled with the login screen and the post-login session, instead of just the post-login session. I can't quite tell why this would occur, and other read_xyz methods also print nothing or have a buffer filled with just the first few bytes of the login screen. My code follows (sensitive data omitted):

def login():
    tn = telnetlib.Telnet(host, port)
    sleep(1)

    tn.write(username + "\t")
    tn.write(password + "\r\n")
    sleep(1)

    data = tn.read_very_eager()

    print data

def main():
    print "started"
    login()

main()

Upvotes: 1

Views: 1437

Answers (1)

Barmar
Barmar

Reputation: 780655

Read the login and password prompts before sending the answers. Otherwise they're kept in the stream and will be read by the next read call.

tn.read_some()
tn.write(username + "\t")
tn.read_some()
tn.write(password + "\r\n")
data = tn.read_some()

And use read_some() instead of read_very_eager() so you don't need to sleep first. It will wait for something to become available, then return everything that's there.

Upvotes: 1

Related Questions