Skip to main content
 首页 » 编程设计

python之使用 Python 通过 ssh 在远程主机上执行本地 shell 函数

2024年10月17日7Terrylee

我的.profile定义了一个函数

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

我想从我的 python 脚本中执行它

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 

请您参考如下方法:

script=''' 
. ~/.profile # load local function definitions so typeset -f can emit them 
ssh user@box ksh -s <<EOF 
$(typeset -f) 
myps 
EOF 
''' 
 
import subprocess 
subprocess.call(['ksh', '-c', script]) # no shell=True 

这里有一些相关的项目:

  • 在您运行 typeset -f 以通过网络转储函数的定义之前,需要在本地调用定义此函数的点文件。。默认情况下,非交互式 shell 不会运行大多数点文件(任何由 ENV 环境变量指定的都是异常(exception))。

    在给定的示例中,这是由 提供的。脚本中的 ~/profile 命令。

  • shell需要是支持typeset的,所以必须是bash或者ksh,而不是sh (默认情况下由 script=True 使用),可能由 ash 或 dash 提供,缺少此功能。

    在给定的示例中,这是通过将 ['ksh', '-c'] 传递给 argv 数组的前两个参数来实现的。

  • typeset 需要在本地运行,因此它不能位于第一个 script=True 以外的 argv 位置。 (举个例子:subprocess.Popen(['''printf '%s\n' "$@"''', 'This is just literal data!', '$(touch/tmp/this- is-not-executed)'], shell=True) 仅评估 printf '%s\n' "$@" 作为 shell 脚本;这只是文字数据! 和 $(touch/tmp/this-is-not-executed) 作为文字数据传递,因此没有名为 /tmp/this-is-not-executed 的文件 被创建)。

    在给定的示例中,这是由不使用 script=True 提出的。

  • 显式调用 ksh -s(或 bash -s,视情况而定)确保评估函数定义的 shell 与您编写的 shell 相匹配 反对这些函数,而不是将它们传递给 sh -c,否则会发生这种情况。

    在给定的示例中,这是由脚本中的 ssh user@box ksh -s 提供的。