Bob Evans
Bob Evans

Reputation: 616

How to chain a ssh, cd, then execution in subprocess.Popen

I'm trying to execute the following code but it is not working

    p = subprocess.Popen("ssh root@IP cd /opt/msys/pe2/bin;./perlscript.pl; -a file.csv", 
                shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

   OR:
   p = subprocess.Popen("ssh root@IP /opt/msys/pe2/bin/perlscript.pl; -a file.csv", 
                shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

The problem with the first is i can seem to chain together commands after ssh. The 2nd is if i call the file directly the -a arg can't find that file because im not in that directory. I was hoping to use the cwd parameter to Popen, but it fails because I'm not ssh'd into the server.

Upvotes: 2

Views: 3253

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226734

Subprocess isn't the best tool for this use case. All the process monitoring options (wait() and terminate() for example) apply to the local process (the ssh session) and not what is happening with the remote script (the perl script for example).

I use fabric to handle running remote scripts. It is easier to use than attempting to string together commands with subprocess.

Upvotes: 2

Scott A
Scott A

Reputation: 7844

Try quoting the command being sent to ssh:

subprocess.Popen('ssh root@IP "cd /opt/msys/pe2/bin;./perlscript.pl;" -a file.csv'

Otherwise you're telling the local shell to do it.

Upvotes: 4

Related Questions