nos*_*nos 2 python ssh subprocess
在我的桌面上,以下 shell 命令列出/aa/*/bb/远程服务器上根目录
ssh my_server 'echo /aa/*/bb/'
Run Code Online (Sandbox Code Playgroud)
但是,当我从 python 子进程调用它时,它报告错误
CalledProcessError: 命令 '['ssh', 'my_server', 'echo /aa/*/bb/']' 返回非零退出状态 255
代码在这里
subprocess.check_output(['ssh', 'my_server', 'echo /aa/*/bb/'], shell=True)
Run Code Online (Sandbox Code Playgroud)
但是,如果我登录到远程服务器并运行
subprocess.check_output('echo /aa/*/bb/', shell=True)
Run Code Online (Sandbox Code Playgroud)
有用。
我做错了什么?非常感谢你的帮助。
您shell=True可以防止传递参数。那是因为:
subprocess.check_output(['ssh', 'my_server', 'echo /*/'], shell=True)
Run Code Online (Sandbox Code Playgroud)
...运行代码:
# /- from shell=True
# | ^ /- your first argument, becomes the script "sh -c" runs
# | | | /- your second argument, becomes $0 to that script
# | | | | /- your third argument, becomes $1 to that script
# | | | | |
sh -c ssh my_server 'echo /*/'
Run Code Online (Sandbox Code Playgroud)
因此,您正在传递您的 shell 脚本(这只是确切的字符串ssh)参数 $0 和 $1,但它根本不读取它们。
如果您希望它与 一起使用shell=True,您可以将其更改为:
# script $0 $1 $2
subprocess.check_output(['ssh "$@"', '_', 'my_server', 'echo /*/'], shell=True)
Run Code Online (Sandbox Code Playgroud)
但更好的是把这个论点排除在外:
subprocess.check_output(['ssh', 'my_server', 'echo /*/'])
Run Code Online (Sandbox Code Playgroud)