Changes between Version 283 and Version 284 of WikiStart


Ignore:
Timestamp:
05/24/2020 10:28:02 PM (6 weeks ago)
Author:
Glyph
Comment:

Add Conch example.

Legend:

Unmodified
Added
Removed
Modified
  • WikiStart

    v283 v284  
    124124    <li><a href="#pubsubserver">Publish/Subscribe</a></li>
    125125    <li><a href="#imap4client">Mail Client</a></li>
     126    <li><a href="#sshclient">SSH Client</a></li>
    126127</ul>
    127128}}}
     
    260261}}}
    261262
     263{{{
     264#!div class="tab-pane" id="sshclient"
     265
     266Twisted includes an SSH client & server, "conch" (i.e.: the Twisted Shell).
     267
     268{{{
     269#!python
     270import sys, os
     271
     272from twisted.internet import protocol, defer, endpoints, task
     273from twisted.conch.endpoints import SSHCommandClientEndpoint
     274
     275async def main(reactor, username="alice", sshhost="example.com", portno="22"):
     276    envAgent = endpoints.UNIXClientEndpoint(reactor, os.environ["SSH_AUTH_SOCK"])
     277    endpoint = SSHCommandClientEndpoint.newConnection(
     278        reactor, "echo 'hello world'", username, sshhost,
     279        int(portno), agentEndpoint=envAgent,
     280    )
     281
     282    class ShowOutput(protocol.Protocol):
     283        received = b""
     284        def dataReceived(self, data):
     285            self.received += data
     286        def connectionLost(self, reason):
     287            finished.callback(self.received)
     288
     289    finished = defer.Deferred()
     290    factory = protocol.Factory.forProtocol(ShowOutput)
     291    await endpoint.connect(factory)
     292    print("SSH response:", await finished)
     293
     294task.react(lambda *a, **k: defer.ensureDeferred(main(*a, **k)), sys.argv[1:])
     295}}}
     296
     297You can use this client to run "hello world" on any SSH server that your local SSH agent can authenticate to, if you pass your username, host name, and optionally port number on the command line.
     298
     299}}}
     300
     301
    262302}}}
    263303