本文共 1376 字,大约阅读时间需要 4 分钟。
>>> help(eval)Help on built-in function eval in module __builtin__:eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.>>>
eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果:
>>> s='8*8'>>> eval(s)64>>> eval('2+5*4')22>>> x=1>>> y=4>>> eval('x+y')5>>> eval('98.9')98.9>>> eval('9.9\n')9.9>>> eval('9.9\n\t\r \t\r\n')9.9可以把list,tuple,dict和string相互转化:
>>> l = "[2,3,4,5]">>> ll=eval(l)>>> ll[2, 3, 4, 5]>>> type(ll)eval()函数功能强大,但也很危险,若程序中有以下语句:>>> d="{'name':'python','age':20}">>> dd=eval(d)>>> type(dd) >>> dd{'age': 20, 'name': 'python'}>>> t='(1,2,3)'>>> tt=eval(t)>>> type(tt) >>> tt(1, 2, 3)>>>
s=raw_input('please input:')print eval(s)下面举几个被恶意用户使用的例子:
1》运行程序,如果用户恶意输入:
please input:__import__('os').system('dir')
则eval()之后,当前目录文件都会展现在用户前面。。。2》运行程序,如果用户恶意输入:
please input:open('data.py').read()
如果,当前目录中恰好有一个文件,名为data.py,则恶意用户变读取到了文件中的内容。。。
3》运行程序,如果用户恶意输入:
please input:__import__('os').system('del delete.py /q')
如果,当前目录中恰好有一个文件,名为delete.py,则恶意用户删除了该文件。。。 /q :指定静音状态。不提示您确认删除。类似文章,请参考:
转载地址:http://cnyai.baihongyu.com/