在调试 Python 程序的时候,一般我们只能通过以下几种方式进行调试:
1. 程序中已经有的日志
2. 在代码中插入 import pdb; pdb.set_trace()
但是以上的方法也有不方便的地方, 比如对于已经在运行中的程序, 就不可能停止程序后加入 调试代码和增加新的日志.
从 JAVA 的 BTrace(https://kenai.com/projects/btrace) 项目得到灵感,尝试对正在运行的 Python 进程插入代码,在程序运行到指定的函数后,自动连接远程主机进行调试
首先介绍三个开源的项目, 本实验需要用到这三个项目
1. Pyasite https://github.com/lmacken/pyrasite Tools for injecting code into running Python processes
2. Byteplay https://github.com/serprex/byteplay 一个字节码维护项目,类似 java的asm/cglib
3. Rpdb-Shell https://github.com/alex8224/Rpdb-Shell
待注入的代码, 用官方的 ``tornado hello demo`` 做例子
import tornado.ioloop import tornado.web import os class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) print(os.getpid()) tornado.ioloop.IOLoop.instance().start()
import sys import dis import inspect from byteplay import * def wearedcode(fcode): c = Code.from_code(fcode) if c.code[1] == (LOAD_CONST, 'injected'): return fcode c.code[1:1] = [ (LOAD_CONST, injected'), (STORE_FAST, 'name'), (LOAD_FAST, 'name'), (PRINT_ITEM, None), (PRINT_NEWLINE, None), (LOAD_CONST, -1), (LOAD_CONST, None), (IMPORT_NAME, 'rpdb'), (STORE_FAST, 'rpdb'), (LOAD_FAST, 'rpdb'), (LOAD_ATTR, 'trace_to_remote'), (LOAD_CONST, '10.86.11.116'), (CALL_FUNCTION, 1), (POP_TOP, None) ] return c.to_code() def trace(frame, event, arg): if event != 'call': return co = frame.f_code func_name = co.co_name if func_name == "write": return if func_name == "get": import tornado.web args = inspect.getargvalues(frame) if 'self' in args.locals: if isinstance(args.locals['self'], tornado.web.RequestHandler): getmethod = args.locals['self'].get code = getmethod.__func__.__code__ getmethod.__func__.__code__ = wearedcode(code) return sys.settrace(trace)