Help needed with controlling the python parser

André andre.roberge at gmail.com
Tue Jan 10 20:22:23 EST 2006


vinjvinj wrote:
> I use python to script my application. Users will be able to write
> their own python scripts which are then run a grid of servers. I want
> to be able to capture syntax errors in submitted users scripts and then
> display them (with line numbers) back to the user.

I was going to wait for other, familiar with pylint, etc. to answer,
but it seems like no-one is attempting to answer your query.  So, here
goes a poor attempt ;-)

>From all I have heard, if you are going to be concerned about safety,
you are pretty much out of luck.  However, assuming you still want to
try it, here's one potential way (untested way) to do it:

.try:
.    exec self.code in MyGlobals  # Define your own dictionary for
added safety...
.except Exception, info:
.    if "invalid syntax" in info:   # to catch it and change the
default message
.        linenumber = info[1][1]
.        print "An error was found on (or before) line: %d"%info[1][1]

>
> I also want to check for obvious things which I'm going to restrict in
> the code. Initially I would like to disallow any imports, and access to
> __* access. I understand that it is near impossible to make the scripts
> run in a completely restricted env.
You could try something like the following untested function:

.def ParseProgram(contents):
.    bad_keywords = ["chr", "exec", "eval", "input", "raw_input",
"import"]
.    for word in bad_keywords:
.        if word in contents:
.            mesg = "Keyword or function not allowed:" + str(word)
.            return False, mesg
.    return True, ''

I would augment it with a regular expression to catch "__*".  [This is
left as an exercise to the reader ;-)]

>
> Is scripting a tool like pylint the way to go? Or is it fairly easy to
> control the python parser to do this?
>
I don't know what pylint can do for you in that regard.
As far as I know, it is near impossible to ensure that you can restrict
a determined user from doing nasty stuff.

> Thanks,
> 
> VJ
André




More information about the Python-list mailing list