Using Plink (PuTTy) to SSH through Python

Jeff picture Jeff · Nov 9, 2011 · Viewed 21.9k times · Source

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?

Answer

Cito picture Cito · Nov 9, 2011

In the second approach, use

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