Home  >  Q&A  >  body text

Hacking - Python module security permissions

Now we need to develop a plug-in system. Anyone in the plug-in system can write PY files and load them. But you need to introduce the library of the main program, such as

# test.py
from lib.function import *
...

How to prevent users from accessing other methods or variables in lib?

all If I add the name, my main program needs to call all *, is it okay?

伊谢尔伦伊谢尔伦2591 days ago556

reply all(1)I'll reply

  • 欧阳克

    欧阳克2017-06-12 09:27:57

    There are no real private variables or methods in python, so basically it is impossible to prevent others from accessing the methods or variables of another module, but if the user imports from lib.function import *, then we can pass __all__ Attributes to set * variables or methods that can be specified by import, for example:

    cat abc.py
    __all__ = ['bar']
    waz = 5
    bar = 10
    def baz(): return 'baz'
    
    cat b2.py
    from abc import *
    print(dir())
    
    # 输出:
    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'bar']

    You can see that the output in b2.py does not have bar and baz, so we can use this method to make a simple control. Of course, private variables starting with an underscore are also restricted, but This restriction is invalid for the import method import abc

    reply
    0
  • Cancelreply