Regarding Telnet library in python

Eddie Corns eddie at holyrood.ed.ac.uk
Wed Aug 13 10:25:41 EDT 2008


Hishaam <hishaam.ab at gmail.com> writes:

>Hi,

>In python documentation, i found a telnet example as follows:

>-------------------------------------------------------------------------
>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")
>tn.write("exit\n")

>print tn.read_all()
>-------------------------------------------------------------------------

>The ouput of it as follows:

>-------------------------------------------------------------------------
>Enter your remote account: root

>Last login: Mon Aug 13 11:54:32 from pcp246879pcs.ca
>Sun Microsystems Inc.   SunOS 5.10      Generic January 2005
># Desktop     boot        hishaam     net         system      work
>Documents   cdrom       home        opt         tfile2      zonemgr
>File.txt    dev         kernel      platform    tmp
>QA_tmp      devices     lib         proc        usr
>acunix      etc         lost+found  sbin        var
>bin         export      mnt         sfile       vol
>#

>-------------------------------------------------------------------------

>The difficulty i find in this is th code line "print tn.read_all()" is
>used for reading all of the output of the code at once.

>Is there a possibility to read the stdout of each command by command
>like -

># ls
><stdout 1>
>[capture <stdout 1> in a variable]
># cd /root
><stdout 2>
>[capture <stdout 2> in a variable]


>Like the above would be useful if there are a large number of commands
>to be executed in the telnet session.

>Can anyone help on this?

>Regards,
>Hishaam

One way of doing this is to send the commands one at a time and do: (untested)

  prompt = '\n# '

  tn.write("ls\n")
  stdout = tn.read_until(prompt)
  for line in stdout.splitlines():
    ...
  etc.

alternatively just send them all in one go as you have been and save the
output in a variable and split that on the prompt.  In either case you may
want to change the prompt to something easier to match on like "$hostname# ".

Eddie



More information about the Python-list mailing list