Reputation: 869
I need to execute a few ssh commands. I have found some example but it is for one command, for example '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)
What should i do to execute 2 commands, for example 'pwd', 'ls'. Should i make 2 endpoints? Will it be right? But it will make 2 ssh connections, isn't it? It seems to me there should be another way to do what i want.
Upvotes: 1
Views: 466
Reputation: 48335
Use SSHCommandClientEndpoint.existingConnection
to run multiple commands over a single SSH connection.
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)
...
Keep in mind that these commands still don't run in the same shell session though. So you may not necessarily find commands like pwd
terrible useful.
If you want to run multiple commands in a single shell session then you need to use shell to combine the commands:
# 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)
...
Upvotes: 3