我怎样才能安全地执行 python 的一个子集? [英] How can I go about securely executing a subset of python?

查看:48
本文介绍了我怎样才能安全地执行 python 的一个子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将基本功能的源代码存储在数据库中,并允许通过管理界面对其进行修改.此代码将多个数字和字符串作为参数,并返回一个数字或 None.我知道 eval 是邪恶的,所以我需要实现一种安全的方式来执行 Python 的一个非常基本的子集,或者至少在基于 Python 的 Web 应用程序中的语法相似.

I need to store source code for a basic function in a database and allow it to be modified through an admin interface. This code will take several numbers and strings as parameters, and return a number or None. I know that eval is evil, so I need to implement a safe way to execute a very basic subset of python, or something syntactically similar at least, from within a python based web-app.

显而易见的答案是实现 DSL(域特定语言),但是,我没有这方面的经验,也不知道从哪里开始,而且许多可用资源似乎超出了我的头.我希望也许已经有一些东西可以让我从数据库中的字符串基本上生成一个安全的 python 可调用函数.该语言实际上只需要支持赋值、基本数学、if/else 和不区分大小写的字符串比较.任何其他功能都是额外的,但我认为大多数事情都可以做到这一点,不需要复杂的数据结构、类、函数等.

The obvious answer is to implement a DSL (Domain Specific Language), however, I have no experience with that, nor do I have any idea where to begin, and a lot of the resources available seem to go a little over my head. I'm hoping that maybe there is something already out there which will allow me to essentially generate a secure python-callable function from a string in a database. the language really only needs to support assignment, basic math, if/else, and case insensitive string comparisons. any other features are a bonus, but I think most things can be done with just that, no need for complex data structures, classes, functions, etc.

如果目前不存在这样的东西,我愿意研究创建一个的可能性,但正如我所说,我不知道如何去做,在这方面的任何建议也将不胜感激.

If no such thing currently exists, I'm willing to look into the possibility of creating one, but as I said, I have no idea how to go about that, and any advice in that regard would be appreciated as well.

推荐答案

你可以使用 Pyparsing实现你的 DSL,前提是所涉及的表达式不会太复杂(你没有提供完整的细节,但你暗示要求非常简单).请参阅示例页面,具体包括fourFn.pysimpleCalc.py.

You could use Pyparsing to implement your DSL, provided the expressions involved won't be too complex (you don't give full details on that but you imply the requirements are pretty simple). See the examples page including specifically fourFn.py or simpleCalc.py.

这篇关于我怎样才能安全地执行 python 的一个子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆