Skip to content Skip to sidebar Skip to footer

Launching 'safe' Eval()

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 someth

Solution 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.

Solution 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

Solution 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).

Solution 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.

Solution 5:

Post a Comment for "Launching 'safe' Eval()"