pexpect ssh login and ls | grep

Cameron Laird claird at lairds.us
Mon Dec 31 17:36:28 EST 2007


In article <3eb81375-3e4a-4e0f-a4e7-bbb1d6cd0f8c at s19g2000prg.googlegroups.com>,
crybaby  <joemystery123 at gmail.com> wrote:
>I need to ssh into a remote machine and check if mytest.log file is
>there.  I have setup ssh keys to handle login authentications.
>
>How do I determine if mytest.log is there by using Pexpect. What I
>have done so far is spawned a child for ssh.
>
>1) Now what do I do to execute shell_cmd(ls and grep), spawn another
>child?
>
>2) Can I use the same child that was spawned for ssh, if so how?
>
>3) After executing the ls -l|grep mystest.log, how do I get the value
>from pexpect?
>
>shell_cmd = 'ls -l | grep mytest.log'
>child = pexpect.spawn ('ssh my at mycomp2')
>#child.sendline(shell_cmd)
>
>>>> child.sendline("ls")
>3
>>>> print child.before
>:~[
>>>> child.after
>'my at mycomp2 '
>
>>>> child.sendline('/bin/bash', ['-c',shell_cmd])
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>TypeError: sendline() takes at most 2 arguments (3 given)
			.
			.
			.
You might like to experiment with this:

    import pexpect

    prompt = '\$ '
    filename = "mytest.log"
    password = "xxxxxx"

    child = pexpect.spawn('ssh -l %s %s ' (user, host))
    child.expect([pexpect.TIMEOUT, '[Pp]assword: '])
    child.sendline(password)
    child.expect([pexpect.TIMEOUT, prompt])
    child.sendline("ls %s > /dev/null 2>&1; echo $?" % filename)
    child.expect([pexpect.TIMEOUT, prompt])
    result = child.before
	# You'll typically see "0" or "2" here, depending on 
	# whether filename exists or not.
    print result.split('\r\n')[1]

Does this leave any questions?



More information about the Python-list mailing list