首页 > 技术文章 > Python eval 作用和风险 (string 转为dict list tuple)建议用“ast.literal_eval”

alamZ 2017-06-13 16:43 原文

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:\AlamTW\study\python

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

推荐阅读