Skip to main content

Python: Wrapping Methods Via a Backdoor

Often, when you write a server in Python, you include a backdoor. The backdoor is something that you can telnet to from localhost, and it's basically a Python shell. Within the Python shell, you can snoop around the running program. It's cool. Now, suppose you want to insert some code to debug a problem. Suppose you want to intercept all method calls to a certain class. (If you're a hardcore Python hacker, feel free to stop reading, but many other people will find this interesting.)

>>> class C:
... """This is some pre-existing class within the running application."""
... def f(self, num): print "I got called with:", num
...
>>>
>>> def wrap(f):
... """This is a function decorator. inner below is the wrapper itself."""
... def inner(*args, **kargs):
... print "I'm about to call %s with %s %s." % ... (f.__name__, `args[1:]`, `kargs`)
... return f(*args, **kargs)
... return inner
...
>>>
>>> # Wrap every method in C.
... for name in dir(C):
... attr = getattr(C, name)
... if callable(attr):
... setattr(C, name, wrap(attr))
...
>>>
>>> # Now, when you call C.f, the method is wrapped.
... C().f(5)
I'm about to call f with (5,) {}.
I got called with: 5

Comments

Ian Bicking said…
Perhaps an interesting way to make a backdoor is something like the console example I have in Paste.

Though if you wanted to watch all print statements, you might want something more chat-like, where the web app pings the server every second or two and shows any newly printed content. Though if you don't do that (and you were using WSGI) you could use something like paste.printdebug, which displays all prints in the webpage itself (assuming this is an in-development app): -- other logging-style collectors would also be neat.

Lastly, the magic_set decorator in ruby_blocks.py is, I think, an interesting way to inject functionality (it should look for a next_method argument, though, which would make it easier to use for this kind of thing).
Your mention of magic set is about how to add a method to a class, right? Yeah, I've faced that problem as well.

I talked about the solution I had for that problem at our Python users' group (basically, I curried the function, manually creating a bound method), but our two Python users' groups are so far away from each other. That is really too bad because we were specifically interested in a talk on SQLObject and other related projects! The funny thing is, that thread happened on our mailing list the same day you announced the next meeting of the Chicago Python users' group!

Yeah, using AJAX for the backdoor is cool, although, since you are enforcing the localhost rule (as am I), it's easier to telnet from localhost than to have a Web browser or HTTP tunnel on localhost. Nonetheless, it's a good technique.