[Tutor] How to import modules using the input() command

Alan Gauld alan.gauld at btinternet.com
Thu Nov 15 23:17:07 CET 2007


"bob gailer" <bgailer at alum.rpi.edu> wrote 

> modname = raw_input()
> exec "import " + modname
> 
> That can be a security risk, in that a use could 
> enter "time; import os; os.rmdir('some_valuable_directory')"

Even more risky is the fact that modules can contain executable 
code that is run when the module is imported. If someone wrote 
such a module they would only need to type the filename and 
the exec would result in the rogue code being executed. If the 
rogue code had the same name as a standard module it would 
be extremely hard to detect. All of which are good reasons 
for not doing this unless you intend to build an IDE or 
somesuch - and even then there are better solutions!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list