Results 1 to 3 of 3

Thread: importing module dynamically in python Share/Save - My123World.Com!

  1. #1
    ... I am no Expert b0nd.g4h@gmail.com b0nd's Avatar
    Join Date
    Jul 2010
    Location
    irc.freenode.net #g4h
    Posts
    744

    importing module dynamically in python

    "python - load modules dynamically"

    Situation is:
    1. You have got a directory where you've python modules. When your fuzzer runs, it shall on-the-fly import modules randomly from that directory and use the fuction(s) existing within them.

    Here you've got two problems:
    1. You do not want to be statically bound to edit your main code everytime you add a new module in directory.
    2. You don't know the functions existing inside your python modules because you don't know the name of randomly picked modules at the first place.

    Requirement:
    Pick any random number of modules from directory and utilize there function to code something as your test cases.

    Solution:
    Code:
    import os
    import glob
    import sys
    import inspect
    import copy
    sys.path.append('modules_fuzz')    
    
        jsCode = ""
    
    
        __file__ = os.path.join(executablePath, fuzzModulesDir + '/')                        
    
    
        allModulesList = []
    
    
        for f in glob.glob(os.path.dirname(__file__)+"/*.py"):                       ## it finds all .py fuzz modules present in fuzzModulesDir directory
            if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
                allModulesList.append(os.path.basename(f)[:-3])        ## allModulesList: ['module1', 'module2', 'module3', ......, 'upto-all-modules']
    
    
            
        for module in allModulesList:
            new_module = __import__(module)                    ## here module is getting imported without specifying actual name
            functionFromModule = inspect.getmembers(new_module, inspect.isfunction)            ## list of all functions from current module
            jsCode += getattr(new_module, functionFromModule[0][0])(argument_to_function)    ## doing operation on function passing it some argument
            i += 1
    [*] To follow the path: look to the master, follow the master, walk with the master, see through the master,
    ------> become the master!!! <------
    [*] Everyone has a will to WIN but very few have the will to prepare to WIN
    [*] Invest yourself in everything you do, there's fun in being serious

  2. #2
    Garage Member
    Join Date
    Aug 2012
    Location
    India
    Posts
    97
    Blog Entries
    1
    Similar can also be achieved using the "imp" module. I have seen this being used in CapTipper. Here's the simple code to load the modules from a directory "modules".

    Code:
    #!/usr/bin/env python
    
    """ 
    This trick is inspired/taken from CapTipper - https://github.com/omriher/CapTipper/blob/master/CTPlugin.py
    """
    
    import glob
    import os
    import imp
    
    module_files = glob.glob("modules/*.py")
    for module in module_files:
        full_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), module)
        print "[+] Importing the module - %s" % full_path
        (path, name) = os.path.split(full_path)
        (name, ext) = os.path.splitext(name)
    
        (p_file, filename, data) = imp.find_module(name, [path])
        try:
            mod = imp.load_module(name, p_file, filename, data)
        except ImportError:
            print "[-] Couldn't import module. Exiting!"
            sys.exit(1)
    
        # After the module is loaded, you can run the desired function. For ex.
        mod.run()
    Using the above trick, you can load the whole module in a variable, lets say "module1" and then it can be used like you would use a module, for ex. module1.function_name( arguments ), module1.variable_name, etc.

    Hope this helps. Cheers.

    Regards,
    c0dist
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who
    keeps learning stays young. The greatest thing in life is to keep your mind young.
    - Henry Ford

  3. #3
    ... I am no Expert b0nd.g4h@gmail.com b0nd's Avatar
    Join Date
    Jul 2010
    Location
    irc.freenode.net #g4h
    Posts
    744
    Thanks for that c0dist. I'll try this out in my next code (who wants to mess with current working code )

    Cheers!
    [*] To follow the path: look to the master, follow the master, walk with the master, see through the master,
    ------> become the master!!! <------
    [*] Everyone has a will to WIN but very few have the will to prepare to WIN
    [*] Invest yourself in everything you do, there's fun in being serious

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •