gpt4 book ai didi

python - SSHCommandClientEndpoint,扭曲。如何执行多个命令?

转载 作者:行者123 更新时间:2023-11-30 23:27:16 26 4
gpt4 key购买 nike

我需要执行一些 ssh 命令。我找到了一些示例,但它适用于一个命令,例如“pwd”:

endpoint = SSHCommandClientEndpoint.newConnection(reactor, 'pwd',
username, host, port,
password=password,
agentEndpoint=agent
)
factory = MonitoringFactory()
d = endpoint.connect(factory)
d.addCallback(lambda protocol: protocol.finished)

我应该怎么做才能执行 2 个命令,例如“pwd”、“ls”。我应该设置 2 个端点吗?会是对的吗?但它会建立 2 个 ssh 连接,不是吗?在我看来应该有另一种方式来做我想做的事。

最佳答案

使用SSHCommandClientEndpoint.existingConnection通过单个 SSH 连接运行多个命令。

from twisted.conch.endpoints import SSHCommandClientEndpoint
from twisted.internet.endpoints import connectProtocol

# Open a connection with a long-running command so that the connection
# is re-usable for other commands indefinitely.
command = b"cat"

endpoint = SSHCommandClientEndpoint.newConnection(
reactor, command, username, host, port,
password=password, agentEndpoint=agent)

connecting = connectProtocol(endpoint, Protocol())
def connected(protocol):
conn = protocol.transport.conn
a = SSHCommandClientEndpoint.existingConnection(conn, b"pwd")
b = SSHCommandClientEndpoint.existingConnection(conn, b"...")
c = SSHCommandClientEndpoint.existingConnection(conn, b"...")
...
connecting.addCallback(connected)
...

请记住,这些命令仍然不会在同一个 shell session 中运行。因此,您可能不一定会发现像 pwd 这样的命令非常有用。

如果您想在单个 shell session 中运行多个命令,那么您需要使用 shell 来组合命令:

# Open a connection with a long-running command so that the connection
# is re-usable for other commands indefinitely.
command = b"pwd; ls foo; cd /tmp"

endpoint = SSHCommandClientEndpoint.newConnection(
reactor, command, username, host, port,
password=password, agentEndpoint=agent)

...

关于python - SSHCommandClientEndpoint,扭曲。如何执行多个命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22196373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com