Scripting SSH with Python

Alex the_brain at mit.edu
Tue Oct 24 16:26:59 EDT 2000


> I am scripting SSH or actually rsync using ssh and I am in need of a
> bit of help.  When I make the SSH connection I am prompted to enter a
> password...  my problem is that I don't know how to look for this
> promt and have the script submit the password for me.  Can anyone give
> me some help on this.

Here's some code that I ripped off another news post ages ago, and
mutated.  Hope it helps.  It requires the pty module.

Alex.

-- 
Speak softly but carry a big carrot.


#!/usr/bin/env python
import os
execfile (os.path.join (os.environ['PYTHONSTARTUP']))

import os, string, pty, time, signal

def remote_ex(hostname, password):
  pid, fd = pty.fork()
  if pid == 0:
    os.execv("/usr/local/bin/ssh",[hostname])
  else:
    time.sleep(2)
    print "Child says %s" % string.strip(os.read(fd,1024))
    # print "Child took %d password bytes." % os.write(fd, password)
    time.sleep(2) #being over cautious
    print "Child took %d command bytes" % \
          os.write(fd, "echo $HOST > ~/ptyhost.txt\n")
    print "Child says %s" % string.strip(os.read(fd,1024))
    print "Child took %d exit bytes." % os.write(fd, "exit\n")
    print "Child says %s" % string.strip(os.read(fd,1024))
    # st ()
    os.kill(pid, signal.SIGKILL)
  return

#=-=-=-=-=-Main=-=-=-=-=-=-=#
def main():
  # myhost = string.strip(raw_input("Enter a host:"))
  # mypass = raw_input("Enter your Password:")
  remote_ex(myhost, mypass)

##########################

if __name__ == "__main__":
  main()




More information about the Python-list mailing list