This will prevent the behaviour @Jochen observed (assuming you populate your list a little more fully)
def __import__(name, globals={}, locals={}, fromlist=[], level=-1, oldfunc=__import__):
checklist = fromlist[:]
checklist.extend(name.split('.'))
for check in checklist:
if check in ('os', 'sys'):
print 'Uh-uh I\'m better than that...'
return
oldfunc(name, globals, locals, fromlist, level)
Trying it on your site gives:
>>> def __import__(name, globals={}, locals={}, fromlist=[], level=-1, oldfunc=__import__):
checklist = fromlist[:]
checklist.extend(name.split('.'))
for check in checklist:
if check in ('os', 'sys'):
print 'Uh-uh I\'m better than that...'
return
oldfunc(name, globals, locals, fromlist, level)
>>> __import__('os')
Uh-uh I'm better than that...
>>> x = [__import__('os')]
Uh-uh I'm better than that...
>>>
It doesn't however change the default import
behaviour. It looks like you're stopping there from being a literal with the name 'os' in it. If you can find a way of editing the actual import
behaviour to call this function (I'm not hopeful that this is even possible, but it's worth looking into) then you can allow literals with names along the lines of dangerous imports - as well as allowing people to use variable names that they like, this will make it harder to work out what you're doing to prevent imports, and therefore getting around it...