Executing python script stored as a string

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Sep 1 05:32:29 EDT 2009


On Tue, 01 Sep 2009 01:34:33 -0700, Ecir Hana wrote:

>> You can copy the parts of the current scope into the namespace you pass
>> to exec, then later copy the revised values out again.
>>
>> But are you sure you really want to take this approach? exec is up to
>> ten times slower than just executing the code directly. And if the
>> string is coming from an untrusted source, it is a *huge* security
>> risk.
> 
> I don't know if I should use exec. I don't really mind that it's slow
> (btw., why is it so?).

Because it has to parse and compile the string into a code object before 
it can run it. 


> But I don't quite understand why is it security
> risk. How is it different to run:
> exec 'format(your_hdd)'
> than:
> /bin/python format.py
> ?

It's not different. But read what I said -- "if the string is coming from 
an UNTRUSTED source" -- presumably you trust yourself. If you run 'exec 
"format(your_hdd)"' it is because *you* want to format your hard disk.

Now imagine you have a web-app which gets a string from the user and 
calls exec on it. Then you might have this:

exec "search('%d')" % user_input

and the user, who is halfway across the world, enters the following 
search string:

places to eat'); import os; os.system('#rm -rf /

Your web app will go right ahead and erase itself. That's why you need to 
keep untrusted strings away from exec, execfile, and eval.



>> As far as I know, you can't kill threads, you can only ask them to kill
>> themselves.
> 
> Also, I'm not sure if I follow. What does this mean? If a thread runs:
> 
> while True:
>   pass
> 
> it is not possible to kill it from another thread? (Bacause it doesn't
> check whether some other thread asks to stop it..?)

No, I believe that the only way to halt that is to halt the entire 
process.

Possibly there is a way to have a thread halt itself after a certain 
amount of time? I'm not an expert on threads, I've hardly ever used them.



-- 
Steven



More information about the Python-list mailing list