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):
 time.sleep(d)

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
 else:
  pause()
  #Get password prompt; ignore
  os.read(fd, 1000)
  pause()
  #write password
  os.write(fd, pw + "\n")
  pause()
  res = ''
  #read response from child process
  s = os.read(fd,1 )
  while s:
   res += s
   s = os.read(fd, 1)
  return res

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

Labels:


Comments: Post a Comment



<< Home

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