how to convert string to list or tuple

Steven Bethard steven.bethard at gmail.com
Sun May 29 16:13:50 EDT 2005


Duncan Booth wrote:
> Dan Bishop wrote:
>> Or if you do use eval, don't give it access to any names.
[snip]
>> os.system("rm -rf *")
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>>   File "<string>", line 0, in ?
>> NameError: name 'os' is not defined
> 
> Have you tried giving it the string '__import__("os").system("rm -rf *")'?
> [Don't try that at home children!]

But you can try it at home if you set __builtins__ to something other 
than the default:

py> eval("""__import__("os").system('echo "hello"')""", 
dict(__builtins__=None))
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<string>", line 0, in ?
NameError: name '__import__' is not defined

If you're just doing work with constants, the lack of access to any 
builtins is ok:

py> eval("(1,2,3)", dict(__builtins__=None))
(1, 2, 3)

I know there have been security holes in this technique before, but I 
looked at the archives, and all the old ones I found have been patched. 
  (Or at least I wasn't able to reproduce them.)

STeVe



More information about the Python-list mailing list