Python
  Home arrow Python arrow Page 4 - SSH with Twisted
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 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: starstarstarstarstar / 6
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    SSH with Twisted - Providing an Administrative Python Shell
    ( Page 4 of 5 )

    Example 10-1 demonstrated how to provide an interactive shell through SSH. That example implemented its own language with a small set of commands. But there’s another kind of shell that you can run over SSH: the same interactive Python prompt you know and love from the command line.

    How Do I Do That?

    The twisted.conch.manhole and twisted.conch.manhole_ssh modules have classes designed to provide a remote interactive Python shell inside your running server. Create a manhole_ssh.TerminalRealm object and set its chainedProtocolFactory.protocolFactory attribute to a function that will return manhole.Manhole objects. Example 10-3 demonstrates a web server that can be modified on the fly using SSH and twisted.conch.manhole .

    Example 10-3. manholeserver.py

    from twisted.internet import reactor
    from twisted.web import server, resource from twisted.cred import portal, checkers from twisted.conch import manhole, manhole_ssh

    class LinksPage(resource.Resource):
        isLeaf = 1

        def __init__(self, links) :
            resource.Resource.__init__(self)
            self.links = links

        def render(self, request):
           
    return "<ul>" + "".join([
               
    "<li><a href='%s'>%s</a></li>" % (link, title)
               
    for title, link in self.links.items()]) + "</ul>"

    links = {'Twisted': 'http://twistedmatrix.com/',
            
    'Python': 'http://python.org'}
    site = server.Site(LinksPage(links)) reactor.listenTCP(8000, site)

        def getManholeFactory(namespace, **passwords):
            realm = manhole_ssh.TerminalRealm()
            def getManhole(_): return manhole.Manhole(namespace) 
      realm.chainedProtocolFactory.protocolFactory = getManhole
            p = portal.Portal(realm)
            p.registerChecker(
               
    checkers.InMemoryUsernamePassword DatabaseDontUse(**passwords))
            f = manhole_ssh.ConchFactory(p)
            return f

    reactor.listenTCP(2222, getManholeFactory(globals(), admin='aaa'))
    reactor.run()

    manholeserver.py will start up a web server on port 8000 and an SSH server on port 2222. Figure 10-1 shows what the home page looks like when the server starts.


    Figure 10-1.  The default manholeserver.py web page

    Now log in using SSH. You’ll get a Python prompt, with full access to all the objects in the server. Try modifying the links dictionary:

      $ ssh admin@localhost -p 2222
      admin@localhost's password:
    aaa

      >>> dir()
      ['LinksPage', '__builtins__', '__doc__', '__file__', '__name_ _', 'checkers',
      'getManholeFactory', 'links', 'manhole', 'manhole_ssh', 'portal', 'reactor',
      'resource', 'server', 'site']
      >>> links
     
    {'Python': 'http://python.org', 'Twisted': 'http://twistedmatrix.com/'}
      >>> links["Abe Fettig"] = http://fettig.net
      >>> links["O'Reilly"] = http://oreilly.com
      >>> links
      {'Python': 'http://python.org', "O'Reilly": 'http://oreilly.com', 'Twisted': 'http:// twistedmatrix.com/', 'Abe Fettig': 'http://fettig.net'}
      >>>

    Then refresh the home page of the web server. Figure 10-2 shows how your changes will be reflected on the web site.


    Figure 10-2.  The modified manholeserver.py web page

    How Does That Work?

    Example 10-3 defines a function called getManholeFactory that makes running a manhole SSH server trivially easy. getManholeFactory takes an argument called namespace , which is a dictionary defining which Python objects to make available, and then a number of keyword arguments representing usernames and passwords. It constructs a manhole_ssh.TerminalRealm and sets its chainedProtocolFactory.protocolFactory attribute to an anonymous function that returns manhole.Manhole objects for the requested namespace. It then sets up a portal using the realm and a dictionary of usernames and passwords, attaches the portal to a
    manhole_ssh.ConchFactory , and returns the factory.

    Like its name implies, manhole provides a portal to something that is off-limits to the she is allowed in, she can do anything she wants. You can pass a dictionary of Python objects as namespace only for the sake of convenience (to limit the set of objects the user has to look through), not for security. Only administrative users should have permission to use the manhole server.

    Example 10-3 creates a manhole factory using the built-in globals() function, which returns a dictionary of all the objects in the current global namespace. When you log in through SSH, you can see all the global objects in manholeserver.py, including the links dictionary. Because this dictionary is also being used to generate the home page of the web site, any changes you make through SSH are instantly reflected on the Web.

    The manhole_ssh.ConchFactory class includes its own default public/private key pair. For your own projects you shouldn’t rely on these built-in keys. Instead, generate your own and set the publicKeys and privateKeys attributes of the ConchFactory . See Example 10-1, earlier in this chapter, for an example of how to do this.



     
     
    >>> More Python Articles          >>> More By O'Reilly Media
     

       

    PYTHON ARTICLES

    - Tuples and Other Python Object Types
    - The Dictionary Python Object Type
    - String and List Python Object Types
    - Introducing Python Object Types
    - Mobile Programming using PyS60: Advanced UI ...
    - Nested Functions in Python
    - Python Parameters, Functions and Arguments
    - Python Statements and Functions
    - Statements and Iterators in Python
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT