如何检测代码变更?
假设有这样的代码:
class X:
def myfunc(self):
print "orig"
def new_myfunc(self):
print "new"
X().myfunc()
X.myfunc = new_myfunc
X().myfunc()
这里的新函数是被一个作弊者注入的。
有些函数可以被修改,有些则不能。
我想知道如何检测到这个代码的变化。
比如,我可以做一个字典,里面存放原始函数的代码(用“func_code”),然后检查它们是否被改变。
但是我该如何在每次“导入”时进行检查呢?有没有办法在Python中编辑自动加载器?
补充:我想要的就是这样,但希望能在每次导入时自动进行检查,怎么做呢?
protection = {'X':'myfunc'}
f = {}
class X:
def myfunc(self):
print "orig"
def new_myfunc(self):
print "new"
#system check
for key,value in protection.iteritems():
protectedFunc = getattr(eval(key), value)
f[key] = { value : protectedFunc.func_code}
#cheater code
X.myfunc = new_myfunc
#system check
for key,value in protection.iteritems():
protectedFunc = getattr(eval(key), value)
if f[key][value] != protectedFunc.func_code:
print 'detected'
#call by my app
X().myfunc()