Using python with SSH?

Martin Franklin mfranklin1 at
Thu Dec 18 11:06:02 CET 2003

On Wed, 2003-12-17 at 23:00, Steve wrote:
> Hi,
> I need to run a remote program from a server that I have access rights 
> to. I want to be able to do this from within in my python script and I 
> want to use ssh (or anything else that will work). However, doing 
> something like:
> ssh -l user host "/path/to/program"
> prompts for a password and I don't know how to supply one via a python 
> script. Is there an easy way out? Can I log onto to the other machine 
> via ssh somehow? Does a python script support this? Thanks!
> Steve


You don't say if you are running on Windows or not but this is a ssh
wrapper I use that uses the pexpect library...:

import pexpect
import sys
import re
import os
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:
        elif i==1:
            self.child.expect("assword:", timeout=120)
    def command(self, command):
        """send a command and return the response"""
        response = self.child.before
        return response
    def close(self):
        """close the connection"""
if __name__=="__main__":
    import getpass
    password = getpass.getpass("Password: ")
    ssh = SSH("RemoteUsername", password, "RemoteHost")
    print ssh.command("pwd")

Martin Franklin <mfranklin1 at>

More information about the Python-list mailing list