我知道以前有人问过这个问题,不过这个案子有点不同。在
我想运行一个python imageboard(使用web.py),它允许用户通过提交代码生成新的图像。代码将采用单个函数的形式,该函数获取像素的x、y坐标并返回r、g、b值,例如:
def simpleGradient(xrel,yrel):
r = xrel*256
g = yrel*256
b = 0
return [r,g,b]
只需要一个非常小的语法,它不一定是python。使用范围有限的exec
似乎太不安全,而使用PyPy或VM似乎不必要地复杂(我对所有这些都很陌生)。在
有没有一种python方法可以用更小的语言来执行代码,而不是用沙箱来处理它?python的一个子集(解析和白名单?),或者我可以嵌入的面向数学的语言?在
有很多很棒的信息on the pysandbox pypi page。在
这就是我的解决方案。有关此方法的安全性的讨论,请参见
多亏了arifwn,我开始研究Python的
ast
(抽象语法树)模块。此模块提供一个用于遍历树的ast.NodeVisitor
。这段代码将NodeVisitor
子类化,以创建一个语法检查器,该检查器将基本数学所需的代码白名单。函数调用和名称是特别监视的,因为只允许某些函数,只允许使用未使用的名称。在请注意,这是为了只接受代码的数学部分而设计的,提供了函数定义和返回语句。在
这种将所有必需的安全构造(尤其是白名单所需的不安全构造)白名单的方法可以修改为生成许多有用的Python子集;非常适合用户脚本!在
注意,为了安全地执行,它应该在它自己的线程中有一个超时,以便在用户代码生成无限循环或类似循环时减少名称冲突和超时。在
相关问题 更多 >
编程相关推荐