[Tutor] Remote access from Windows PC to a Linux box

Tim Golden mail at timgolden.me.uk
Wed Mar 31 14:42:27 CEST 2010


On 30/03/2010 17:29, Mike Baker wrote:
> I'm trying to connect to a Linux box from my Windows machine and execute a
> series of commands
>
> I want a script to always
> execute the same series of commands without having to do so manually.   I
> also have code that will execute a single command like cat a file and write
> the ouput to a new file. However, when I try to use the communicate object
> in subprocess, my window hangs.


This works for me:

<code>
import os, sys
import subprocess

PLINK = "plink"
REMOTE_USER = "tgolden at web30.webfaction.com"
PIPE = subprocess.PIPE

p = subprocess.Popen ([PLINK, REMOTE_USER, "ls"], stdout=PIPE)
stdout, stderr = p.communicate ()
print "#1:", stdout.splitlines ()[0]

with open ("out.txt", "w") as f:
   p = subprocess.Popen ([PLINK, REMOTE_USER, "cat .bashrc"], stdout=f)
   p.communicate ()
print "#2:", open ("out.txt").read ().splitlines ()[0]

p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
stdout, stderr = p.communicate ("ls\nexit\n")
print "#3", stdout

p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
p.stdin.write ("ls\nexit\n")
stdout, stderr = p.communicate ()
print "#4", stdout

</code>

A few things to note, none of which I believe to be germane to the
issues you're experiencing:

* You almost never need to use shell=True on a Windows call to subprocess.
   If in doubt, don't use it.

* Definitely better to pass the list-of-params style as the first param
   of subprocess.Popen; it sorts out issues with embedded spaces etc.

* The open ("...", "w") in your second example *may* be closing the
   file immediately. I doubt it, since you'd expect Popen to hold a
   reference, but I haven't checked the implementation.

TJG


More information about the Tutor mailing list