Python
  Home arrow Python arrow SSH with Twisted
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
eWeek
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

SSH with Twisted
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-03-06

    Table of Contents:
  • SSH with Twisted
  • Setting Up a Custom SSH Server continued
  • Using Public Keys for Authentication
  • Providing an Administrative Python Shell
  • Running Commands on a Remote Server

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
     
    ADVERTISEMENT

    TestComplete™ automates software testing for a fraction of what the big guys charge. Easy functional and load testing for all Windows, .NET, Java and Web apps. Download a free trial now.

    SSH with Twisted
    (Page 1 of 5 )

    Twisted is a framework for networked applications. In this article, you'll learn how to use the Secure Shell (SSH) with Twisted to accomplish a variety of useful tasks. This article is excerpted from chapter 10 of the book Twisted Network Programming Essentials, written by Abe Fettig (O'Reilly, 2007; ISBN: 0596100329). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    SSH, the Secure SHell, is an essential tool for many developers and administrators. SSH provides a way to establish encrypted, authenticated connections. The most common use of an SSH connection is to get a remote shell, but it’s possible to do many other things through SSH as well, including transferring files and tunneling other connections.

    The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules intwisted.conchto build SSH servers and clients.

    Setting Up a Custom SSH Server

    The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.

    You can usetwisted.conchto create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.

    How Do I Do That?

    Write a subclass of  twisted.conch.recvline.HistoricRecvLinethat implements your shell protocol.HistoricRecvLineis similar totwisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

    Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

    To make your shell available through SSH, you need to implement a few different classes thattwisted.conchneeds to build an SSH server. First, you need thetwisted.credauthentication classes: a portal, credentials checkers, and a realm that returns avatars. Usetwisted.conch.avatar.ConchUseras the base class for your avatar. Your avatar class should also implementtwisted.conch.interfaces.ISession, which includes anopenShell method in which you create aProtocolto manage the user’s interactive session. Finally, create atwisted.conch.ssh.factory.SSHFactoryobject and set itsportalattribute to an instance of your portal.

    Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.

    Example 10-1. sshserver.py

    from twisted.cred import portal, checkers, credentials
    from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
    from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
    from zope.interface import implements
    import os

    class SSHDemoProtocol(recvline.HistoricRecvLine):
        def __init__(self, user):
            self.user = user

        def connectionMade(self): 
         recvline.HistoricRecvLine.connectionMade(self)
            self.terminal.write("Welcome to my test SSH server.")
            self.terminal.nextLine()
            self.do_help()
            self.showPrompt()

        def showPrompt(self):
            self.terminal.write("$ ")

        def getCommandFunc(self, cmd):
            return getattr(self, 'do_' + cmd, None)

        def lineReceived(self, line):
            line = line.strip()
            if line:
               
    cmdAndArgs = line.split()
                cmd = cmdAndArgs[0]
                args = cmdAndArgs[1:]
                func = self.getCommandFunc(cmd)
                if func:
                  
    try:
                       func(*args)
                   except Exception, e:
                       self.terminal.write("Error: %s" % e)
                       self.terminal.nextLine()
                else:
                   self.terminal.write("No such command.")
                   self.terminal.nextLine()
            self.showPrompt()

        def do_help(self, cmd=''):
            "Get help on a command. Usage: help command"
            if cmd:
               
    func = self.getCommandFunc(cmd)
                if func:
                    self.terminal.write(func.__doc__)
                    self.terminal.nextLine()
                    return

            publicMethods = filter(
               
    lambda funcname: funcname.startswith('do_'), dir(self))
            commands = [cmd.replace('do_', '', 1) for cmd in publicMethods]
            self.terminal.write("Commands: " + " ".join(commands))
            self.terminal.nextLine()

        def do_echo(self, *args):
            "Echo a string. Usage: echo my line of text"
            self.terminal.write(" ".join(args))
            self.terminal.nextLine()

        def do_whoami(self):
            "Prints your user name. Usage: whoami"
            self.terminal.write(self.user.username)
            self.terminal.nextLine()

        def do_quit(self):
            "Ends your session. Usage: quit"
            self.terminal.write("Thanks for playing!")
            self.terminal.nextLine()
            self.terminal.loseConnection()

        def do_clear(self):
            "Clears the screen. Usage: clear"
            self.terminal.reset()

    class SSHDemoAvatar(avatar.ConchUser):
        implements(conchinterfaces.ISession)

        def __init__(self, username):
            avatar.ConchUser.__init__(self)
            self.username = username
            self.channelLookup.update({'session':session.SSHSession})

        def openShell(self, protocol):
            serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
            serverProtocol.makeConnection(protocol)
            protocol.makeConnection(session.wrapProtocol(serverProtocol))

        def getPty(self, terminal, windowSize, attrs):
            return None

        def execCommand(self, protocol, cmd):
            raise NotImplementedError

        def closed(self):
            pass

    class SSHDemoRealm:
        implements(portal.IRealm)

        def requestAvatar(self, avatarId, mind, *interfaces):
            if conchinterfaces.IConchUser in interfaces:
                return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
            else:
                raise Exception, "No supported interfaces found."

    def getRSAKeys():
       
    if not (os.path.exists('public.key') and os.path.exists('private.key')):
            # generate a RSA keypair
            print "Generating RSA keypair..."
            from Crypto.PublicKey import RSA
            KEY_LENGTH = 1024
            rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
            publicKeyString = keys.makePublicKeyString(rsaKey)
            privateKeyString = keys.makePrivateKeyString(rsaKey)
            # save keys for next time
            file('public.key', 'w+b').write(publicKeyString)
            file('private.key', 'w+b').write(privateKeyString)
            print "done."
       
    else:
            publicKeyString = file('public.key').read()
            privateKeyString = file('private.key').read()
       
    return publicKeyString, privateKeyString

    if __name__ == "__main__":
        sshFactory = factory.SSHFactory()
        sshFactory.portal = portal.Portal(SSHDemoRealm())
        users = {'admin': 'aaa', 'guest': 'bbb'}
        sshFactory.portal.registerChecker(
     
    checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

        pubKeyString, privKeyString =
    getRSAKeys()
        sshFactory.publicKeys = {
            'ssh-rsa': keys.getPublicKeyString(data=pubKeyString)}
        sshFactory.privateKeys = {
            'ssh-rsa': keys.getPrivateKeyObject(data=privKeyString)}

        from twisted.internet import reactor
        reactor.listenTCP(2222, sshFactory)
        reactor.run()

    More Python Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Twisted Network Programming Essentials,"...
     

    Buy this book now. This article is excerpted from chapter 10 of the book Twisted Network Programming Essentials, written by Abe Fettig (O'Reilly, 2007; ISBN: 0596100329). Check it out today at your favorite bookstore. Buy this book now.

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway