ssh and Python

iwk iwk_removethis at xs4all_removethisalso.nl
Mon Jul 22 10:39:09 EDT 2002


edadk wrote:
> I would like to write script that using ssh automatically execute
> commands commands on a remote machine. How can I do that?

Use the following function 'rcmd' to execute commands on a server 
through SSH with password authentication (better to use keys, but that's 
not always an option)

The trick is to use os.forkpty because ssh will not read stdin for the 
password, but rather directly from the terminal.

It works on Unix and on Windows through Cygwin (not directly on Win32 
because it lacks the os.forkpty() implementation)

Regards,

Iwan

#!/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'])





More information about the Python-list mailing list