[Tutor] Help with pexpect

vince spicer vinces1979 at gmail.com
Fri Oct 16 22:33:36 CEST 2009


On Fri, Oct 16, 2009 at 1:45 PM, Nathan Farrar <nathan.farrar at gmail.com>wrote:

> I'm trying to automate the collection of data to remote devices over
> ssh via pexpect.  I had originally attempted (with limited success) to
> use paramiko, however due to cisco's ssh implimentation I cannot send
> mulitple commands over the same connection, which is absolutely
> essential.  Therefore, I'm now attempting to use pexpect, but am
> having trouble getting started.  I have a simple script, such as:
>
> session = pexpect.spawn('ssh user at host')
> session.expect([pexpect.TIMETOUT, 'password:'])
> session.send('password')
> print session.read() # shouldn't this display the logon banner & command
> prompt?
> session.close()
>
> This code results in no output & a hanging window. What am I doing
> incorrect?
>
> Additionally, I will need to add conditional pexpect statements, such
> that when I execute a command I want to gather the output, however if
> '--More--' is encountered (and it this can happen multiple times), I
> want to send a newline character to the session and continue gathering
> the output.
>
> Thanks for the help!
> Nathan
>
> --
> "The presence of those seeking the truth is infinitely to be preferred
> to the presence of those who think they've found it."
>
> –Terry Pratchett
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

when using pexpect for ssh you can run into some issues, I have used to
script some elaborate green screen apps, but not without some unforeseen
bugs

when connecting to a new machine, most ssh client will ask you verify the
fingerprint

something like:

> are you sure you want to continue (yes/no)?

also session.send < doesn't send eol "\n" but sendline does

So this should fix your connection

###
session = pexpect.spawn('ssh user at host')
i = session.expect([pexpect.TIMETOUT, 'password:', "yes/no"])
if i == 2:
    session.sendline("yes")
    session.expect([pexpect.TIMETOUT, 'password:'])
if i == 1:
    session.sendline('password')
    print session.read() # shouldn't this display the logon banner & command
prompt?
session.close()
###

the other your question,  pexpects sendline(''), will just send a newline

not perfect but should work
###
license = ""
while True:
    i = session.expect(["--more--", "yes/no"])
    if i == 1:
       break
    license += session.before
    session.sendline('')
###


Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091016/06f00931/attachment-0001.htm>


More information about the Tutor mailing list