zoukankan      html  css  js  c++  java
  • Python eval 作用和风险 (string 转为dict list tuple)建议用“ast.literal_eval”

    a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
    
    b = eval(a)
    
    print b

    [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
    [Finished in 0.2s]

    a = "{1: 'a', 2: 'b'}"  
    b = eval(a)
    print b
    print type(b)

    {1: 'a', 2: 'b'}
    <type 'dict'>
    [Finished in 0.2s]

    -----风险-------

    eval强大的背后,是巨大的安全隐患!!! 比如说,用户恶意输入下面的字符串

    open(r'D://filename.txt', 'r').read()

    __import__('os').system('dir')

    __import__('os').system('rm -rf /etc/*')

    a = "__import__('os').system('dir')"  
    b = eval(a)
    print b
    print type(b)
    

    Volume in drive D has no label.
    Volume Serial Number is 66B4-8B5C

    Directory of D:AlamTWstudypython

    13/06/2017 PM 03:23 <DIR> .
    13/06/2017 PM 03:23 <DIR> ..
    14/03/2017 PM 05:20 1,388 20170314-1.py
    01/04/2017 PM 03:20 2,180 20170401.py
    16/05/2017 PM 02:47 386 20170516unittest.py
    21/04/2017 AM 10:57 147 testDemo.yaml
    21/04/2017 AM 11:18 525 yaml_python.py
    14/03/2017 PM 01:44 <DIR> __pycache__
    38 File(s) 27,575 bytes
    8 Dir(s) 390,064,582,656 bytes free
    0
    <type 'int'>
    [Finished in 0.3s]

    ------所以用ast.literal_eval代替----

    import ast
    
    a = "open('test.py').read()"  
    # b = eval(a)
    b = ast.literal_eval(a)
    print b
    print type(b)
    

    ValueError: malformed string

  • 相关阅读:
    cocos2dx Menu
    关于iOS招聘面试的一些问题
    OC画图
    iOS苹果产品简介
    iOS知识小总结
    @property的修饰参数的的解释
    IOS:UI设计之UINavigationController,NavigationBar,ToolBAR相关基础
    IOS:UI设计之UISegmentedControl相关基础
    IOS:UI设计之UISlider相关基础
    IOS:UI设计之UILable相关基础
  • 原文地址:https://www.cnblogs.com/alamZ/p/7002093.html
Copyright © 2011-2022 走看看