python eval()函数的妙用和滥用

>>> 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)
<type 'list'>
>>> d="{'name':'python','age':20}"
>>> dd=eval(d)
>>> type(dd)
<type 'dict'>
>>> dd
{'age': 20, 'name': 'python'}
>>> t='(1,2,3)'
>>> tt=eval(t)
>>> type(tt)
<type 'tuple'>
>>> tt
(1, 2, 3)
>>> 
eval()函数功能强大,但也很危险,若程序中有以下语句:

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 :指定静音状态。不提示您确认删除。


类似文章,请参考:Python之eval()函数的危险




  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值