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

标签 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 连接,不是吗?在我看来应该有另一种方式来做我想做的事。

最佳答案

使用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/

相关文章:

python - 连接到在(有时是虚拟化)Windows 计算机上运行的服务器时出现问题

python - 通过 python (msn) 发送即时消息

Python Spyder 初始化 Hello World Kivi 应用程序一次?

python - python中的最小二乘法

svn - Xcode svn+ssh 自定义端口不工作?

linux - 如何通过带有参数的 ssh 执行远程命令?

python - Pandas :加入外部产品

python - asn1 将文本解析为 json

java - 通过ssh在远程系统上执行java代码

python - 在扭曲中使用我自己的主循环