ssh control from Python
Chuck Esterbrook
ChuckEsterbrook at yahoo.com
Thu Jul 26 09:04:11 EDT 2001
I'm trying to control ssh from Python using pty. I have made some progress.
For example, if I send the wrong password, I get a message back saying so.
However, after sending the correct password, sent commands just get echoed
back to me.
I verified that I can use ssh from the command prompt, both by specifying
the remote command as an extra arg to ssh and through the interactive shell.
I'm really close, but obviously still missing something.
I'm using Python 2.1 and Linux Mandrake 7.2 (kernel 2.2.17 I think).
#!/usr/bin/env python
# original version by Alex (the_brain at mit.edu) per 2000/10/24 c.l.p
import os, pty, time, signal
def remote_ex(hostname, password, cmd):
pid, fd = pty.fork()
if pid==0:
os.execv("/usr/bin/ssh", ['/usr/bin/ssh', hostname])
else:
password += '\n'
cmd += '\n'
delay = 3
time.sleep(delay)
print ">> 1 Child says %r" % os.read(fd,1024).strip()
print ">> 2 Child took %d password bytes." % os.write(fd, password)
time.sleep(delay) # being over cautious
print ">> 3 Child took %d command bytes" % os.write(fd, cmd)
print ">> 4 Child says %r" % os.read(fd,1024).strip()
print ">> 5 Child took %d exit bytes." % os.write(fd, "exit\n")
print ">> 6 Child says %r" % os.read(fd,1024).strip()
# st ()
os.kill(pid, signal.SIGKILL)
def main():
cmd = 'echo $HOST > foo.text'
host = 'my.host.com'
pass = 'password'
remote_ex(host, pass, cmd)
if __name__ == "__main__":
main()
The output:
$ ./ssh.py
>> 1 Child says "user at my.host.com's password:"
>> 2 Child took 7 password bytes.
>> 3 Child took 22 command bytes
>> 4 Child says 'echo $HOST > foo.text'
>> 5 Child took 5 exit bytes.
>> 6 Child says 'exit'
If I send the wrong password:
>> 1 Child says "user at my.host.com's password:"
>> 2 Child took 8 password bytes.
>> 3 Child took 22 command bytes
>> 4 Child says "Permission denied, please try
again.\r\r\nuser at my.host.com's password:"
>> 5 Child took 5 exit bytes.
>> 6 Child says ''
So sent commands are echoed back to me instead of being executed with their
output sent back.
Any ideas?
-Chuck
More information about the Python-list
mailing list