Launching 'safe' eval()

三世轮回 提交于 2019-12-24 07:38:00

问题


I m making a irc bot https://github.com/mouuff/MouBot I would like the bot to reply the eval() when the message starts with !math but its creating failures if the user enter something like !math exit() and stuff like that


回答1:


Don't.

It looks like you are trying to create a math parser. Then use a math parser, not a full-fledged I-will-run-any-code-parser. If you are using *nix, you could use a program like bc to do what you want.




回答2:


Use the language services to compile it into an AST, walk the AST making sure that it contains only whitelisted node sets, then execute it.

Example implementation courtesy of unutbu




回答3:


The issue with eval() is that when it is executed, it is valid python code, and the exit() is a valid part of python code, which usually exit's a program (although this specific function should be used in IDLE, and sys.exit() is preffered in non-idle use).

For this reason, eval() should only be used with trusted input, or you should implement a parser for the commands passed to the eval() function, as to elliminate undesirable input (possibly take a look at the shlex module for their split() function if you wish to implement your own, I have used it for many parsers).




回答4:


If you want simple math evaluation why you want to bring whole might of Python behind it, which can and will be abused.

Use something like PyParsing to write a simple calculator e.g. see SimpleCalc.py or fournfn.py , I think those would be enough to get you started. You can also try SimpleParse

and if you DO want to provide eval like powerful and abusable feature, you should start a VM, in which start server processes which will reply to eval queries, and also limit each process using cgroups, when VM goes down start another one or keep a pool of VM and eval processes.




回答5:


I am not sure it could help you but look at this -> http://doc.pypy.org/en/latest/sandbox.html

or this -> Is there an alternative to rexec for Python sandboxing?



来源:https://stackoverflow.com/questions/13211846/launching-safe-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!