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

2024-10-01 02:39:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要执行一些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)

例如,pwi应该执行什么命令。我应该做两个端点吗?对吗?但是它可以建立2个ssh连接,不是吗?在我看来,应该有另一种方法来做我想做的事。在


Tags: 命令hostportfactorypwdusernamepasswordprotocol
1条回答
网友
1楼 · 发布于 2024-10-01 02:39:46

使用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会话中运行。因此,您可能不一定会发现pwd之类的命令非常有用。在

如果要在单个shell会话中运行多个命令,则需要使用shell组合命令:

^{pr2}$

相关问题 更多 >