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

时间:2014-03-05 11:26:44

标签: python ssh twisted endpoint

我需要执行一些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连接,不是吗?在我看来应该有另一种方式来做我想要的。

1 个答案:

答案 0 :(得分:3)

使用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来组合命令:

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

...