问题描述
我需要使用 subprocess
模块在 ssh 会话中执行多个 shell 命令.我可以一次执行一个命令:
I need to execute multiple shell commands in a ssh session using the subprocess
module.I am able to execute one command at a time with:
subprocess.Popen(["ssh", "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", "%s" % <HOST>, <command>])
但是有没有办法在 ssh 会话中使用 subprocess
执行多个 shell 命令?如果可能,我不想使用包.
But is there a way to execute multiple shell commands with subprocess
in a ssh session? If possible, I don't want to use packages.
非常感谢!
推荐答案
严格来说,无论您在远程服务器上执行多少条命令,您都只能使用 Popen
执行一个命令.该命令是 ssh
.
Strictly speaking you are only executing one command with Popen
no matter how many commands you execute on the remote server. That command is ssh
.
要在远程服务器上执行多个命令,只需将它们传递到由 ;
s 分隔的 command
字符串中:
To have multiple commands executed on the remote server just pass them in your command
string seperated by ;
s:
commands = ["echo 'hi'", "echo 'another command'"]
subprocess.Popen([
"ssh",
"-o UserKnownHostsFile=/dev/null",
"-o StrictHostKeyChecking=no",
";".join(commands)
])
如果您希望每个命令仅在前一个命令成功时执行,您也可以在 &&
上加入命令.
You could alternatively join commands on &&
if you wanted each command to only execute if the previous command had succeeded.
如果您有很多命令并且您担心可能会超出 命令行限制,您可以在远程服务器上使用 -s
选项执行 sh
(或 bash),这将在您发送命令时一一执行:
If you have many commands and you are concerned that you might exceed the command line limits, you could execute sh
(or bash) with the -s
option on the remote server, which will execute commands one-by-one as you send them:
p = subprocess.Popen([
"ssh",
"-o UserKnownHostsFile=/dev/null",
"-o StrictHostKeyChecking=no",
"sh -s",
], stdin=subprocess.PIPE)
for command in commands:
p.stdin.write(command)
p.stdin.write("\n")
p.flush()
p.communicate()
请注意,在 Python3 中,您需要将命令编码为字节字符串 (command.encode("utf8")
),然后再将其写入到子进程
.
Note that in Python3 you will need to encode the command to a byte string (command.encode("utf8")
) before writing it to the stdin
of the subprocess
.
尽管最初的建议最简单,但我觉得这对于大多数简单的情况来说都是过度的.
I feel like this is overkill for most simple situations though where the initial suggest is simplest.
这篇关于使用 Python 子进程使用 ssh 的多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!