8

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?

Jeff
  • 12,147
  • 10
  • 51
  • 87
  • 3
    Not an answer - but why bother using `plink` and `putty` when you could use [paramiko](http://www.lag.net/paramiko/) or potentially [fabric](http://docs.fabfile.org/en/1.3.2/index.html)? – wkl Nov 09 '11 at 16:19
  • @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 Nov 09 '11 at 16:22
  • 1
    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 Nov 09 '11 at 16:24

3 Answers3

7

In the second approach, use

ff.communicate("open vnc://www.example.com\n")
Cito
  • 5,365
  • 28
  • 30
  • Was just typing in my own answer to this problem! The problem was that I needed a newline (\n) at the end of the statement. I thought .flush() would do that, but it does not. However I prefer to use stdin.write so that it does not close the subprocess. Thanks! – Jeff Nov 09 '11 at 16:37
0

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

hum3
  • 1,563
  • 1
  • 14
  • 21
-1

I'd try :

Popen("plink user@host -i key.ppk", shell=True)
Popen("open vnc://www.example.com", shell=True)
dugres
  • 12,613
  • 8
  • 46
  • 51
  • I can't Popen the second line because it's not a local command. Anyway, this didn't work but did help me pinpoint the solution by printing out the output from plink! – Jeff Nov 09 '11 at 16:34