本文最后更新于2015年8月2日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!


在Freebuf上看到的两篇文章:Python eval的常见错误封装及利用原理Python安全编码与代码审计,里面涉及到了对Python的eval函数的说明和讲解,之后我又去网上搜了一些资料,整理成了这篇文章。


python eval literal_eval

# Python中的eval是用来干嘛的?
# eval是非常危险的
# 用 eval / ast.literal_eval 来操作json数据?
# Python eval的常见错误封装及利用原理


答:eval() 将第一个字符串参数解释为Python代码并执行。


The eval function lets a python program run python code within itself.eval example (interactive shell):


eval() interprets a string as code. The reason why so many people have warned you about using this is because a user can use this as an option to run code on the computer. If you have eval(input()) and os imported, a person could type into input() os.system(‘rm -R *’) which would delete all your files in your home directory. (Assuming you have a unix system). Using eval() is a security hole. If you need to convert strings to other formats, try to use things that do that, like int().



The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Passing __import__(‘os’).system(‘rm -rf /’) into ast.literal_eval() will raise an error, but eval() will happily wipe your drive.

Since it looks like you’re only letting the user input a plain dictionary, use ast.literal_eval(). It safely does what you want and nothing more.


You cannot secure eval with a blacklist approach like this. See Eval really is dangerous for examples of input that will segfault the CPython interpreter, give access to any class you like, and so on.


Note that this doesn’t protect you from CPU or memory resource attacks (for example, something like:

will most likely cause your program to run out of memory after a while)






这个restrictected mode简单理解就是Python解释器的沙盒,一些功能被限制了,比如说不能修改系统,不能使用一些系统函数,如file,详情见Restricted Execution Mode,那怎么去绕过呢?这时我们就想到了zipimporter了,假如引入的模块中引用了os模块,我们就可以进行利用了。也就是说刚才的safe_eval其实是不安全的。

  1. 使用ast.literal_eval
  2. 如果仅仅是将字符转为dict,可以使用json格式


声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!



电子邮件地址不会被公开。 必填项已用*标注