Thursday, February 02, 2006


Controlling ssh from (python) script

It appears ssh only reads its password from the TTY making it difficult to supply one via a script. Here is a possible solution in python:

The trick is, of course, to create pseudo-TTY:

#!/usr/bin/env python
#Remote command through SSH using user/password
import os, time

def pause(d=0.2):

def rcmd(user, rhost, pw, cmd):
 #Fork a child process, using a new pseudo-terminal as the child's 
controlling terminal.
 pid, fd = os.forkpty()
 # If Child; execute external process
 if pid == 0:
  os.execv("/bin/ssh", ["/bin/ssh", "-l", user, rhost] + cmd)
 #if parent, read/write with child through file descriptor
  #Get password prompt; ignore, 1000)
  #write password
  os.write(fd, pw + "\n")
  res = ''
  #read response from child process
  s =,1 )
  while s:
   res += s
   s =, 1)
  return res

#Example: execute ls on server ''
print rcmd('username', '', 'Password', ['ls -l'])


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?