Jam Jam - 4 months ago 19
Python Question

Executing a local shell function on a remote host over ssh using Python

My

.profile
defines a function

myps () {
ps -aef|egrep "a|b"|egrep -v "c\-"
}


I'd like to execute it from my python script

import subprocess
subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True)


Getting an error back

bash: -c: line 0: syntax error near unexpected token `;'
bash: -c: line 0: `; myps'


Escaping ; results in

bash: ;: command not found

Answer

The original command was not interpreting the ; before myps properly. Using sh -c fixes that, but... ( please see Charles Duffy comments below ).

Using a combination of single/double quotes sometimes makes the syntax easier to read and less prone to mistakes. With that in mind, a safe way to run the command ( provided the functions in .profile are actually accessible in the shell started by the subprocess.Popen object ):

subprocess.call('ssh user@box "$(typeset -f); myps"', shell=True),  

An alternative ( less safe ) method would be to use sh -c for the subshell command:

subprocess.call('ssh user@box "sh -c $(echo typeset -f); myps"', shell=True) 
# myps is treated as a command

This seemingly returned the same result:

subprocess.call('ssh user@box "sh -c typeset -f; myps"', shell=True) 

There are definitely alternative methods for accomplishing these type of tasks, however, this might give you an idea of what the issue was with the original command.