Trouble using telentlib

Kartic removethis.kartic.krishnamurthy at gmail.com
Fri Feb 11 22:11:04 EST 2005


Nitin Chaumal said the following on 2/11/2005 5:41 PM:
> I sarched the existing threads but didnt find an answer to this.
> 
> I am writing simple script which uses telentlib to open a session with
> a unix machine and run "tail -f logfile.txt" on one of the logfiles.
> 
> import telnetlib
> 
> HOST = "192.X.X.X"
> user = "myname"
> password = "mypass"
> 
> tn = telnetlib.Telnet(HOST)
> 
> tn.read_until("login: ")
> tn.write(user + "\n")
> if password:
>     tn.read_until("Password: ")
>     tn.write(password + "\n")
> 
> tn.write("tail -f /tmp/logfile.txt\n")
> 
> # what do i write here ? #
> 
> tn.write("exit\n")
> 

Nitin,

You can not have two writes together. Reads and writes should alternate.

To get the log file this is what you should do:

# Modified my working version for your purpose.
# Hope there are not errors!

def SaveLog(user, password):
     telnet_resp = []
     tn = telnetlib.Telnet(host)

     tn.read_until("login: ")
     tn.write(user + "\n")
     if password:
         telnet_resp.append( tn.read_until("Password: ") )
         tn.write(password + "\n")


     tn.read_until("$ ")
     tn.write("tail -f /tmp/logfile.txt\n")
     telnet_resp.append(tn.read_until("$ "))
     tn.write("exit\n")

     telnet_resp.append(tn.read_all() )
     tn.close()


     telnet_out = open(OUTPUT, 'a')
     telnet_out.write('\n'.join(telnet_resp))
     telnet_out.close()


Alternatively, if your box has FTP access, you can FTP the log file to a 
CStringIO file and operate on it.

Thanks,
-Kartic



More information about the Python-list mailing list