简体   繁体   English

使用Python子进程使用ssh的多个命令

[英]Multiple commands with ssh using Python subprocess

I need to execute multiple shell commands in a ssh session using the subprocess module. 我需要使用subprocess模块在ssh会话中执行多个shell命令。 I am able to execute one command at a time with: 我可以一次执行一个命令:

   subprocess.Popen(["ssh",  "-o UserKnownHostsFile=/dev/null", "-o StrictHostKeyChecking=no", "%s" % <HOST>, <command>])

But is there a way to execute multiple shell commands with subprocess in a ssh session? 但是有没有办法在ssh会话中使用subprocess执行多个shell命令? If possible, I don't want to use packages. 如果可能的话,我不想使用包。

Thank you very much! 非常感谢你!

Strictly speaking you are only executing one command with Popen no matter how many commands you execute on the remote server. 严格来说,无论您在远程服务器上执行多少命令,您只能使用Popen执行一个命令。 That command is ssh . 那个命令是ssh

To have multiple commands executed on the remote server just pass them in your command string seperated by ; 要在远程服务器上执行多个命令,只需在command字符串中分隔; s: 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. 您也可以在&&上加入命令,如果您希望每个命令仅在前一个命令成功时执行。

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: 如果您有许多命令并且您担心可能超出命令行限制 ,则可以使用远程服务器上的-s选项执行sh (或bash),这将在您发送时逐个执行命令:

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()

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 . 请注意,在Python3中,您需要将命令编码为字节字符串( command.encode("utf8") ),然后再将其写入subprocess进程的stdin

I feel like this is overkill for most simple situations though where the initial suggest is simplest. 我觉得这对于大多数简单的情况来说都是过度的,尽管最初的建议是最简单的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM