Launching 'safe' eval()

2019-08-14 11:53发布

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

5条回答
beautiful°
2楼-- · 2019-08-14 12:25

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楼-- · 2019-08-14 12:26

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楼-- · 2019-08-14 12:30
手持菜刀,她持情操
5楼-- · 2019-08-14 12:43

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.

查看更多
劫难
6楼-- · 2019-08-14 12:46

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.

查看更多
登录 后发表回答