I don't know about the best way.. I use this function, it works ok for
me.  I have an ssh key stashed already for my user ID, but you could
look at the ssh options and supply one on the command line if you
needed to.

from popen2 import Popen3

def ssh(host,command) :
    ''' Wraps ssh commands '''
    ssh_exec = ['/usr/bin/ssh -qnx -F ssh_config', host, command]
    cmd = ' '.join(ssh_exec)
    output,errors,status = process(cmd)
    return output,errors,status

def process(cmd) :
    proc = Popen3(cmd,-1)
    output = proc.fromchild.readlines()
    errors = proc.childerr.readlines()
    status = proc.poll()
    return output,errors,status

I somtimes call ssh via a Thread object if I need to run a few at the same time.

In regards to your question,  fork() creates a complete copy of the
running process, and returns a 0 in the child (copy).  The parent gets
the PID of the child as a return code.  I don't think there's anything
wrong with what you are doing though.  I just found that the popen2
module was the easiest to deal with.  subprocess is nice, if you have
2.5, but I have to keep 2.3 ish most of the time.

The function above could theoretically block if the error pipe gets
full before I get to reading it.  I can't recall ever getting that
much back on stderr though.. so I'm taking the chance.

Eric


On Tue, Apr 29, 2008 at 9:29 PM, gert <[EMAIL PROTECTED]> wrote:
> Is this the best way to use ssh ?
>  How can i use ssh keys instead of passwords ?
>  I dont understand what happens when pid does not equal 0 , where does
>  the cmd get executed when pid is not 0 ?
>  How do you close the connection ?
>
>  # http://mail.python.org/pipermail/python-list/2002-July/155390.html
>  import os, time
>
>  def ssh(user, rhost, pw, cmd):
>         pid, fd = os.forkpty()
>         if pid == 0:
>                 os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + cmd)
>         else:
>                 time.sleep(0.2)
>                 os.read(fd, 1000)
>                 time.sleep(0.2)
>                 os.write(fd, pw + "\n")
>                 time.sleep(0.2)
>                 res = ''
>                 s = os.read(fd, 1)
>                 while s:
>                         res += s
>                         s = os.read(fd, 1)
>                 return res
>
>  print ssh('username', 'serverdomain.com', 'Password', ['ls -l'])
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to