Basic Telnet help.

Now I need to use the telnet lib to execute some commands check the output and send some new commands.

The idea was to use the simple example code from the ref.
And add the commands I need to use then check the output and send some more commands. Some of the result printouts are pretty large. I've tried to use the different read_ objects but I don't understand how it's working.
For longer printouts it hangs. And I've only been able to print the result after closing the connection.

I'd be grateful for any example code or a hint to documents which can explain in a simple way how to do it.

Code:

import getpass
import sys
import telnetlib
HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls\n")
# Here I'd like to read and act on the output without first closing the telnet connection.
#How to do it?
#Also more commands with sometimes pretty long output will be used. I like to send the commands after I've had a look at the result from previous command.
tn.write("exit\n")
print tn.read_all()

I looked at the telenetlib docs - I was planning to investigate the code but the number of things I would need to do (all related to compromsing my security made me stop.

Two things occur to me as possibilities:

1. If the telnet object buffers output I would use read_until with an EOL and just read lines into a list.
2. If there is no buffer I would periodically call read_very_eager or read_lazy and append the result to my own buffer from which I read out lines.

The documentation is not fantastic but you can look at the source and you will see how each of the different read methods work. For example I see that read_eager eventually calls read_very_lazy!

Please keep in mind that telnet is about as safe as posting $1000 cash in a transparent envelope. It really shouldn't be used ever. Seriously - not ever. Replace it with SSH ( there's a library here ).