pythonwise / backdoor.py

#!/usr/bin/env python
'''A "backdoor" shell for running servers (very much like Twisted manhole).

This one uses only modules found in the standard library.
'''

from SocketServer import StreamRequestHandler, TCPServer, ThreadingMixIn
from threading import Thread
from traceback import print_exc

EOF = chr(4)

class PyHandler(StreamRequestHandler):

    def handle(self):
        env = self.env.copy()
        self.wfile.write("Welcome to backdoor (type 'exit()' to exit)")
        while True:
            try:
                self.wfile.write(">>> ")
                expr = self.rfile.readline().rstrip()
                if expr == EOF:
                    return
                try:
                    value = eval(expr, globals(), env)
                    self.wfile.write(format(value) + "\n")
                except:
                    exec expr in env
            except (EOFError, SystemExit):
                return
            except Exception as e:
                print_exc(file=self.wfile)

class ThreadedServer(ThreadingMixIn, TCPServer):
    daemon_threads = True

def server_thread(env, port):
    class Handler(PyHandler):
        env = env
    server = ThreadedServer(("localhost", port), Handler)
    server.serve_forever()

DEFAULT_PORT = 9998
def serve(env, port=DEFAULT_PORT):
    t = Thread(target=server_thread, args=(env, port))
    t.daemon = True
    t.start()

    return t

if __name__ == "__main__":
    env = {"a" : 1}
    t = serve(env)
    t.join()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.