[Tutor] Evaluating a string expression
Modulok
modulok at gmail.com
Fri Nov 6 01:54:31 CET 2009
[snip]
> I would like to know how would I evaluate a string expression in python.
> For example, if i say:
>>>> a = "3*2"
> I want to do something to evaluate the variable 'a' to give me 6. How
> can I do this?
[/snip]
The eval() function can do this:
eval("3*2")
WARNING: Long winded security rant below...
Be *very* careful what strings you pass to eval(). It is executing
code! If you're doing this in a controlled environment it's not a
problem. If this is part of a bigger program which is going to be used
by other people, perhaps even online, this is a potentially *huge*
security risk. You will either have to very carefully parse the users
input to control what they can and cannot do, or better, strictly
control what the kernel permits the process to do. This includes what
hardware resources (memory/processor time) the process is allowed.
This way, even if (when) the process is hijacked, the damage will be
very limited.
Such a feat is accomplished by having the program execute as a user
who has very limited permissions. This is something best (only?) done
on UNIX/Linux/BSD flavored systems. This could be done via a setuid
binary, or a *carefully written* root process which immediately
demotes its privilege level upon execution/spawning of children. (Such
a model is employed by programs like apache's httpd server, where one
process is root owned and does nothing but spawn lesser privileged
processes to handle untrusted data.) If this is something you're
interested in, the os module features functions like, 'setuid()',
'setgid()', and notably 'chroot()'. For further security yet, you
might look into isolating a process from the rest of the system, as is
the case with FreeBSD's jails.
These are really big topics and in the end, it really depends on what
'untrusted source' constitutes, and your operating environment.
Writing bulletproof code in regards to security is challenging. It is
a very specialized topic worthy of further study. But in most
situations executing code from an untrusted source is a *really* bad
idea, even with precautions as those outlined in the example URL
provided by one of the other responses.
(http://effbot.org/zone/librarybook-core-eval.htm)
Sorry for all the lecture. I'll shut up now. :p
-Modulok-
More information about the Tutor
mailing list