使用Python通过SSH在远程主机上执行本地Shell函数 [英] Executing a local shell function on a remote host over ssh using Python
问题描述
我的.profile
定义了一个函数
myps () {
ps -aef|egrep "a|b"|egrep -v "c\-"
}
我想从我的python脚本中执行它
I'd like to execute it from my python script
import subprocess
subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True)
找回错误
bash: -c: line 0: syntax error near unexpected token `;'
bash: -c: line 0: `; myps'
转义;导致
bash: ;: command not found
推荐答案
原始命令未正确解释;
之前的;
.使用sh -c
可以解决此问题,但是...(请参阅下面的Charles Duffy评论).
The original command was not interpreting the ;
before myps
properly. Using sh -c
fixes that, but... ( please see Charles Duffy comments below ).
有时使用单引号/双引号的组合会使语法更易于阅读并且不易出错.考虑到这一点,一种安全的命令运行方式(只要.profile
中的功能实际上可以在subprocess.Popen对象启动的外壳中访问):
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),
另一种(不太安全)的方法是对子shell命令使用sh -c
:
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.
这篇关于使用Python通过SSH在远程主机上执行本地Shell函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!