Python:使评估安全 [英] Python: make eval safe

查看:64
本文介绍了Python:使评估安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一种简单的方法在Python中执行计算器API".

I want an easy way to do a "calculator API" in Python.

现在,我不太在乎计算器将支持的确切功能集.

Right now I don't care much about the exact set of features the calculator is going to support.

我希望它接收一个字符串,例如"1+1",并返回一个包含结果的字符串,在我们的例子中是"2".

I want it to receive a string, say "1+1" and return a string with the result, in our case "2".

是否有办法使eval对于这种事情安全?

Is there a way to make eval safe for such a thing?

一开始我会做

env = {}
env["locals"]   = None
env["globals"]  = None
env["__name__"] = None
env["__file__"] = None
env["__builtins__"] = None

eval(users_str, env)

以便调用者无法弄乱我的局部变量(或查看它们).

so that the caller cannot mess with my local variables (or see them).

但是我敢肯定,我在这里监督很多.

But I am sure I am overseeing a lot here.

eval的安全性问题是否可以解决?或者是否有太多微小的细节使它无法正常工作?

Are eval's security issues fixable or are there just too many tiny details to get it working right?

推荐答案

eval的安全性问题是否可解决或 有太多微小的细节吗 使其正常工作?

are eval's security issues fixable or are there just too many tiny details to get it working right?

绝对是后者-一个聪明的黑客将始终设法找到一种预防措施.

Definitely the latter -- a clever hacker will always manage to find a way around your precautions.

如果您对仅使用基本类型文字的普通表达式感到满意,请使用 ast.literal_eval -这就是它的作用!对于任何更喜欢的东西,我建议您使用一个解析包,例如 ply .经典的lexx/yacc方法,或者 pyparsing 可能是更Python化的方法.

If you're satisfied with plain expressions using elementary-type literals only, use ast.literal_eval -- that's what it's for! For anything fancier, I recommend a parsing package, such as ply if you're familiar and comfortable with the classic lexx/yacc approach, or pyparsing for a possibly more Pythonic approach.

这篇关于Python:使评估安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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