ssh

Karthik Gurusamy kar1107 at gmail.com
Wed Apr 30 19:20:58 EDT 2008


On Apr 29, 6:29 pm, gert <gert.cuyk... at gmail.com> 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'])

If ssh is being used interactively (such as being prompted from
password), look into pexpect module.
http://www.noah.org/wiki/Pexpect

Else try the subprocess module (or even commands module); these are
lot simpler to program than the more primitive os.execv/os.read/write.

If you have already setup keys, ssh should work passwordless whether
it's interactive or not (AFAIK).

Karthik



More information about the Python-list mailing list