8
votes

I am trying to write a python script that will SSH to a server and execute a command. I am using Python 2.6 on Windows, and have installed plink and paegent (for ssh keys) and added them all to my path.

If I go to the command prompt and type:

plink username@host -i key.ppk
open vnc://www.example.com/

I see the desired behavior-- a VNC viewer opens on my Mac (server).

However, if I have tried two approaches to do this programmatically through Python and neither is working:

Approach 1 (os):

import os
ff=os.popen("plink user@host -i key.ppk",'w')
print >>ff, r"open vnc://www.example.com"
ff.flush() 

Approach 2 (subprocess):

import subprocess
ff=subprocess.Popen("plink user@host -i key.ppk",shell=False,stdin=subprocess.PIPE)
ff.stdin.write(r"open vnc://www.example.com")
ff.stdin.flush()

Neither approach produces an error, but neither opens the VNC window. However, I believe they both successfully connect to the remote host.

What am I doing wrong?

3
Not an answer - but why bother using plink and putty when you could use paramiko or potentially fabric? - wkl
@birryree i am already using Popen to open the VNC server on windows, so it occurred to me first. i haven't heard of paramiko or fabric, but i will give it a try, thanks! - Jeff
since you want to execute commands via SSH, Fabric is definitely what you want. It's really nice for automation because you can get the stdout of the remote server, execute commands, use sudo, etc. Paramiko is an SSH-wrapper library and Fabric is built on top of it. - wkl

3 Answers

7
votes

In the second approach, use

ff.communicate("open vnc://www.example.com\n")
0
votes

I use fabric for automation of runnning commands via SSH on a remote PC.

-1
votes

I'd try :

Popen("plink user@host -i key.ppk", shell=True)
Popen("open vnc://www.example.com", shell=True)