天天看点

python远程执行shell命令_使用Python通过SSH在远程主机上执行本地Shell函数

python远程执行shell命令_使用Python通过SSH在远程主机上执行本地Shell函数

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 [email protected] \"$(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

解决方案

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 [email protected] "$(typeset -f); myps"', shell=True),

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

subprocess.call('ssh [email protected] "sh -c $(echo typeset -f); myps"', shell=True)

# myps is treated as a command

This seemingly returned the same result:

subprocess.call('ssh [email protected] "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.