Pexpect: SSH, Command and Password

Gil_H gil.horen at gmail.com
Wed Apr 4 13:24:43 CEST 2007


Hi,

I'm trying to run a script over unix on a remote machine.
In order to automate it, the procedure requests the following:
1. Using SSH connection.
2. Operating a command on the remote machine.
3. Expecting password or (yes/no) request and authorize it.

I get an error (I thing that it occures at the last part (3) of the
password request).
I don't have any errors when trying to operate the script without the
last password.
Here is the script:

import pexpect
import sys
import re
import os
import getopt

PROMPT = "\$|\%|\>"


class SSH:
        def __init__(self, user, password, host):
                self.child = pexpect.spawn("ssh %s@%s"%(user, host))
                i = self.child.expect(['assword:', r'yes/no'],
timeout=120)
                if i==0:
                        self.child.sendline(password)
                elif i==1:
                        self.child.sendline("yes")
                        self.child.expect("assword:", timeout=120)
                        self.child.sendline(password)
                        self.child.expect(PROMPT)

        def command(self, command, password):
                """send a command and return the response"""
                self.child.expect(PROMPT)
                self.child.sendline(command)
                j = self.child.expect(['assword:', r'yes/no'],
timeout=120)
                if j==0:
                        self.child.sendline(password)
                elif j==1:
                        self.child.sendline("yes")
                        self.child.expect("assword:", timeout=120)
                        self.child.sendline(password)
                        self.child.expect(PROMPT)

        #       response = self.child.before
        #       return response

        def close(self):
                """close the connection"""
                self.child.close()


if __name__=="__main__":

        ssh = SSH(sys.argv[1], sys.argv[2], sys.argv[3])
        command=sys.argv[4]
        print command
        print "Password: " + sys.argv[2]
        responce=ssh.command(command, sys.argv[2])
        ssh.close()
        print responce


I'm waiting for your ideas.
Thanks,
Gil H.




More information about the Python-list mailing list