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.protocolFactoryattribute to a function that will returnmanhole.Manholeobjects. Example 10-3 demonstrates a web server that can be modified on the fly using SSH andtwisted.conch.manhole. Example 10-3. manholeserver.py from twisted.internet import reactor class LinksPage(resource.Resource): def __init__(self, links): def render(self, request): links = {'Twisted': 'http://twistedmatrix.com/', def getManholeFactory(namespace, **passwords): reactor.listenTCP(2222, getManholeFactory(globals(), admin='aaa')) 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.
Now log in using SSH. You’ll get a Python prompt, with full access to all the objects in the server. Try modifying thelinksdictionary: $ ssh admin@localhost -p 2222 >>> dir() Then refresh the home page of the web server. Figure 10-2 shows how your changes will be reflected on the web site.
Example 10-3 defines a function called getManholeFactory that makes running a manhole SSH server trivially easy. getManholeFactorytakes an argument callednamespace, which is a dictionary defining which Python objects to make available, and then a number of keyword arguments representing usernames and passwords. It constructs amanhole_ssh.TerminalRealmand sets itschainedProtocolFactory.protocolFactoryattribute to an anonymous function that returnsmanhole.Manholeobjects 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 Like its name implies,manholeprovides 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 asnamespaceonly 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 themanholeserver. Example 10-3 creates a manhole factory using the built-inglobals()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 thelinksdictionary. 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.
blog comments powered by Disqus |
|
|
|
|
|
|
|