コード例 #1
0
	def testTwoStepsLoad(self):
		"""
		Test loading the plugins in two steps in order to collect more
		deltailed informations.
		"""
		spm = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# trigger the first step to look up for plugins
		spm.locatePlugins()
		# make full use of the "feedback" the loadPlugins can give
		# - set-up the callback function that will be called *before*
		# loading each plugin
		callback_infos = []
		def preload_cbk(plugin_info):
			callback_infos.append(plugin_info)
		# - gather infos about the processed plugins (loaded or not)
		loadedPlugins = spm.loadPlugins(callback=preload_cbk)
		self.assertEqual(len(loadedPlugins),1)
		self.assertEqual(len(callback_infos),1)
		self.assertEqual(loadedPlugins[0].error,None)
		self.assertEqual(loadedPlugins[0],callback_infos[0])
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
		sole_category = spm.getCategories()[0]
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
		plugin_info = spm.getPluginsOfCategory(sole_category)[0]
		# try to remove it and check that is worked
		spm.removePluginFromCategory(plugin_info,sole_category)
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),0)
		# now re-add this plugin the to same category
		spm.appendPluginToCategory(plugin_info,sole_category)
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
コード例 #2
0
ファイル: test_ErrorInPlugin.py プロジェクト: ysdhaixin/yapsy
    def testTwoStepsLoadWithError(self):
        """
		Test loading the plugins in two steps in order to collect more
		deltailed informations and take care of an erroneous plugin.
		"""
        spm = PluginManager(directories_list=[
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
        ],
                            plugin_info_ext="yapsy-error-plugin")
        # trigger the first step to look up for plugins
        spm.locatePlugins()
        # make full use of the "feedback" the loadPlugins can give
        # - set-up the callback function that will be called *before*
        # loading each plugin
        callback_infos = []

        def preload_cbk(i_plugin_info):
            callback_infos.append(i_plugin_info)

        callback_after_infos = []

        def postload_cbk(i_plugin_info):
            callback_after_infos.append(i_plugin_info)

        # - gather infos about the processed plugins (loaded or not)
        # and for the test, monkey patch the logger
        originalLogLevel = log.getEffectiveLevel()
        log.setLevel(logging.ERROR)
        errorLogCallFlag = [False]

        def errorMock(*args, **kwargs):
            errorLogCallFlag[0] = True

        originalErrorMethod = log.error
        log.error = errorMock
        try:
            loadedPlugins = spm.loadPlugins(callback=preload_cbk,
                                            callback_after=postload_cbk)
        finally:
            log.setLevel(originalLogLevel)
            log.error = originalErrorMethod
        self.assertTrue(errorLogCallFlag[0])
        self.assertEqual(len(loadedPlugins), 1)
        self.assertEqual(len(callback_infos), 1)
        self.assertTrue(isinstance(callback_infos[0].error, tuple))
        self.assertEqual(loadedPlugins[0], callback_infos[0])
        self.assertTrue(issubclass(callback_infos[0].error[0], ImportError))
        self.assertEqual(len(callback_after_infos), 0)
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
コード例 #3
0
ファイル: test_SimplePlugin.py プロジェクト: sueastside/yapsy
    def testMultipleCategoriesForASamePlugin(self):
        """
		Test that associating a plugin to multiple categories works as expected.
		"""
        class AnotherPluginIfce(object):
            def __init__(self):
                pass

            def activate(self):
                pass

            def deactivate(self):
                pass

        spm = PluginManager(categories_filter={
            "Default": IPlugin,
            "IP": IPlugin,
            "Other": AnotherPluginIfce,
        },
                            directories_list=[
                                os.path.join(
                                    os.path.dirname(os.path.abspath(__file__)),
                                    "plugins")
                            ])
        # load the plugins that may be found
        spm.collectPlugins()
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 3)
        categories = spm.getCategories()
        self.assertTrue("Default" in categories)
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory("Default")), 1)
        plugin_info = spm.getPluginsOfCategory("Default")[0]
        self.assertTrue("Default" in plugin_info.categories)
        self.assertTrue("IP" in plugin_info.categories)
        self.assertTrue("IP" in categories)
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory("IP")), 1)
        self.assertTrue("Other" in categories)
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory("Other")), 0)
        # try to remove the plugin from one category and check the
        # other category
        spm.removePluginFromCategory(plugin_info, "Default")
        self.assertEqual(len(spm.getPluginsOfCategory("Default")), 0)
        self.assertEqual(len(spm.getPluginsOfCategory("IP")), 1)
        # now re-add this plugin the to same category
        spm.appendPluginToCategory(plugin_info, "Default")
        self.assertEqual(len(spm.getPluginsOfCategory("Default")), 1)
        self.assertEqual(len(spm.getPluginsOfCategory("IP")), 1)
コード例 #4
0
class ExtInfoTest(unittest.TestCase):
	def setUp(self):
		# create the plugin manager - use the base plugin manager to
                # remove any unecessary dependencies
		self.simplePluginManager = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"Plugins")
			       ], 
                              plugin_info_ext="mm-plugin",
			)
    		#Set mode to test info class
		self.simplePluginManager.setPluginInfoClass(ExtensionInfo)

		# load the plugins that may be found
		self.simplePluginManager.collectPlugins()
		# Will be used later
		self.plugin_info = None


	def loading_check(self):
		"""
		Test the plugins load.
		"""
		if self.plugin_info is None:
			# check nb of categories
			self.assertEqual(len(self.simplePluginManager.getCategories()),1)
			sole_category = self.simplePluginManager.getCategories()[0]
			# check the number of plugins
			self.assertEqual(len(self.simplePluginManager.getPluginsOfCategory(sole_category)),2)
			self.plugin_info = [ None , None ]
			self.plugin_info[0] = self.simplePluginManager.getPluginsOfCategory(sole_category)[0]
			self.plugin_info[1] = self.simplePluginManager.getPluginsOfCategory(sole_category)[1]
			# test that the name of the plugin has been correctly defined
			self.assertTrue("FirstPlugin" in [x.name for x in  self.plugin_info])
			self.assertEqual(sole_category,self.plugin_info[0].category)
		else:
			self.assert_(True)

		
	def testBasic(self):
		self.loading_check()

	def testKnownHash(self):
		"""
		Test hash can be fetched thru ExtensionInfo
                """
		self.loading_check()
		hash1=ExtensionSecureID.fromPathName(self.plugin_info[0].path+".py")
		self.assertEquals(hash1,self.plugin_info[0].getSecureID())
		self.assertNotEquals(self.plugin_info[0].getSecureID(),self.plugin_info[1].getSecureID())
コード例 #5
0
	def testRecursivePluginlocation(self):
		"""
		Test detection of plugins which by default must be
		recusrive. Here we give the test directory as a plugin place
		whereas we expect the plugins to be in test/plugins.
		"""
		spm = PluginManager(directories_list=[
					os.path.dirname(os.path.abspath(__file__))])
		# load the plugins that may be found
		spm.collectPlugins()
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
		sole_category = spm.getCategories()[0]
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
コード例 #6
0
ファイル: test_SimplePlugin.py プロジェクト: sueastside/yapsy
    def testRecursivePluginlocation(self):
        """
		Test detection of plugins which by default must be
		recusrive. Here we give the test directory as a plugin place
		whereas we expect the plugins to be in test/plugins.
		"""
        spm = PluginManager(
            directories_list=[os.path.dirname(os.path.abspath(__file__))])
        # load the plugins that may be found
        spm.collectPlugins()
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 1)
コード例 #7
0
    def test_init_with_plugin_locator(self):
        class SpecificLocator(IPluginLocator):
            pass

        pm = PluginManager(plugin_locator=SpecificLocator())
        self.assertEqual(["Default"], pm.getCategories())
        self.assertTrue(isinstance(pm.getPluginLocator(), SpecificLocator))
コード例 #8
0
	def testMultipleCategoriesForASamePlugin(self):
		"""
		Test that associating a plugin to multiple categories works as expected.
		"""
		class AnotherPluginIfce(object):
			def __init__(self):
				pass
			def activate(self):
				pass
			def deactivate(self):
				pass

		spm = PluginManager(
			categories_filter = {
				"Default": IPlugin,
				"IP": IPlugin,
				"Other": AnotherPluginIfce,
				},
			directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# load the plugins that may be found
		spm.collectPlugins()
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),3)
		categories = spm.getCategories()
		self.assertTrue("Default" in categories)
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory("Default")), 1)
		plugin_info = spm.getPluginsOfCategory("Default")[0]
		self.assertTrue("Default" in plugin_info.categories)
		self.assertTrue("IP" in plugin_info.categories)
		self.assertTrue("IP" in categories)
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory("IP")),1)
		self.assertTrue("Other" in categories)
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory("Other")),0)
		# try to remove the plugin from one category and check the
		# other category
		spm.removePluginFromCategory(plugin_info, "Default")
		self.assertEqual(len(spm.getPluginsOfCategory("Default")), 0)
		self.assertEqual(len(spm.getPluginsOfCategory("IP")), 1)
		# now re-add this plugin the to same category
		spm.appendPluginToCategory(plugin_info, "Default")
		self.assertEqual(len(spm.getPluginsOfCategory("Default")),1)
		self.assertEqual(len(spm.getPluginsOfCategory("IP")),1)
コード例 #9
0
    def testTwoStepsLoadWithError(self):
        """
		Test loading the plugins in two steps in order to collect more
		deltailed informations and take care of an erroneous plugin.
		"""
        spm = PluginManager(
            directories_list=[os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")],
            plugin_info_ext="yapsy-error-plugin",
        )
        # trigger the first step to look up for plugins
        spm.locatePlugins()
        # make full use of the "feedback" the loadPlugins can give
        # - set-up the callback function that will be called *before*
        # loading each plugin
        callback_infos = []

        def preload_cbk(i_plugin_info):
            callback_infos.append(i_plugin_info)
            # - gather infos about the processed plugins (loaded or not)
            # and for the test, monkey patch the logger

        originalLogLevel = log.getEffectiveLevel()
        log.setLevel(logging.ERROR)
        errorLogCallFlag = [False]

        def errorMock(*args, **kwargs):
            errorLogCallFlag[0] = True

        originalErrorMethod = log.error
        log.error = errorMock
        try:
            loadedPlugins = spm.loadPlugins(callback=preload_cbk)
        finally:
            log.setLevel(originalLogLevel)
            log.error = originalErrorMethod
        self.assertTrue(errorLogCallFlag[0])
        self.assertEqual(len(loadedPlugins), 1)
        self.assertEqual(len(callback_infos), 1)
        self.assertTrue(isinstance(callback_infos[0].error, tuple))
        self.assertEqual(loadedPlugins[0], callback_infos[0])
        self.assertEqual(callback_infos[0].error[0], ImportError)
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
コード例 #10
0
    def testTwoStepsLoad(self):
        """
		Test loading the plugins in two steps in order to collect more
		deltailed informations.
		"""
        spm = PluginManager(directories_list=[
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
        ])
        # trigger the first step to look up for plugins
        spm.locatePlugins()
        # make full use of the "feedback" the loadPlugins can give
        # - set-up the callback function that will be called *before*
        # loading each plugin
        callback_infos = []

        def preload_cbk(plugin_info):
            callback_infos.append(plugin_info)

        callback_after_infos = []

        def postload_cbk(plugin_info):
            callback_after_infos.append(plugin_info)

        # - gather infos about the processed plugins (loaded or not)
        loadedPlugins = spm.loadPlugins(callback=preload_cbk,
                                        callback_after=postload_cbk)
        self.assertEqual(len(loadedPlugins), 1)
        self.assertEqual(len(callback_infos), 1)
        self.assertEqual(loadedPlugins[0].error, None)
        self.assertEqual(loadedPlugins[0], callback_infos[0])
        self.assertEqual(len(callback_after_infos), 1)
        self.assertEqual(loadedPlugins[0], callback_infos[0])
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 1)
        plugin_info = spm.getPluginsOfCategory(sole_category)[0]
        # try to remove it and check that is worked
        spm.removePluginFromCategory(plugin_info, sole_category)
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
        # now re-add this plugin the to same category
        spm.appendPluginToCategory(plugin_info, sole_category)
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 1)
コード例 #11
0
ファイル: test_SimplePlugin.py プロジェクト: sueastside/yapsy
    def testNonRecursivePluginlocationNotFound(self):
        """
		Test detection of plugins when the detection is non recursive.
		Here we test that it cannot look into subdirectories of the
		test directory.
		"""
        pluginLocator = PluginFileLocator()
        pluginLocator.setPluginPlaces(
            [os.path.dirname(os.path.abspath(__file__))])
        pluginLocator.disableRecursiveScan()
        spm = PluginManager()
        spm.setPluginLocator(pluginLocator)
        # load the plugins that may be found
        spm.collectPlugins()
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
コード例 #12
0
	def testNonRecursivePluginlocationNotFound(self):
		"""
		Test detection of plugins when the detection is non recursive.
		Here we test that it cannot look into subdirectories of the
		test directory.
		"""
		pluginLocator = PluginFileLocator()
		pluginLocator.setPluginPlaces([
					os.path.dirname(os.path.abspath(__file__))])
		pluginLocator.disableRecursiveScan()
		spm = PluginManager()
		spm.setPluginLocator(pluginLocator)
		# load the plugins that may be found
		spm.collectPlugins()
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
		sole_category = spm.getCategories()[0]
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),0)
コード例 #13
0
    def testDisablingRecursivePluginLocationAllowsFindingTopLevelPlugins(self):
        """
		Test detection of plugins when the detection is non
		recursive. Here we test that if we give test/plugin as the
		directory to scan it can find the plugin.
		"""
        pluginLocator = PluginFileLocator()
        pluginLocator.setPluginPlaces([
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
        ])
        pluginLocator.disableRecursiveScan()
        spm = PluginManager()
        spm.setPluginLocator(pluginLocator)
        # load the plugins that may be found
        spm.collectPlugins()
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 1)
コード例 #14
0
	def testCategoryManipulation(self):
		"""
		Test querying, removing and adding plugins from/to a category.
		"""
		spm = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# load the plugins that may be found
		spm.collectPlugins()
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
コード例 #15
0
ファイル: test_SimplePlugin.py プロジェクト: PGower/yapsy
	def testDisablingRecursivePluginLocationAllowsFindingTopLevelPlugins(self):
		"""
		Test detection of plugins when the detection is non
		recursive. Here we test that if we give test/plugin as the
		directory to scan it can find the plugin.
		"""
		pluginLocator = PluginFileLocator()
		pluginLocator.setPluginPlaces([
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		pluginLocator.disableRecursiveScan()
		spm = PluginManager()
		spm.setPluginLocator(pluginLocator)
		# load the plugins that may be found
		spm.collectPlugins()
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
		sole_category = spm.getCategories()[0]
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
コード例 #16
0
ファイル: test_SimplePlugin.py プロジェクト: sueastside/yapsy
    def testCategoryManipulation(self):
        """
		Test querying, removing and adding plugins from/to a category.
		"""
        spm = PluginManager(directories_list=[
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
        ])
        # load the plugins that may be found
        spm.collectPlugins()
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 1)
        plugin_info = spm.getPluginsOfCategory(sole_category)[0]
        # try to remove it and check that is worked
        spm.removePluginFromCategory(plugin_info, sole_category)
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
        # now re-add this plugin the to same category
        spm.appendPluginToCategory(plugin_info, sole_category)
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 1)
コード例 #17
0
	def testCategoryManipulation(self):
		"""
		Test querying, removing and adding plugins from/to a category.
		"""
		spm = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# load the plugins that may be found
		spm.collectPlugins()
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
		sole_category = spm.getCategories()[0]
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
		plugin_info = spm.getPluginsOfCategory(sole_category)[0]
		# try to remove it and check that is worked
		spm.removePluginFromCategory(plugin_info,sole_category)
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),0)
		# now re-add this plugin the to same category
		spm.appendPluginToCategory(plugin_info,sole_category)
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
コード例 #18
0
    def testChangingCategoriesFilter(self):
        """
		Test the effect of setting a new category filer.
		"""
        spm = PluginManager(directories_list=[
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
        ])
        # load the plugins that may be found
        spm.collectPlugins()
        newCategory = "Mouf"
        # Pre-requisite for the test
        previousCategories = spm.getCategories()
        self.assertTrue(len(previousCategories) >= 1)
        self.assertTrue(newCategory not in previousCategories)
        # change the category and see what's happening
        spm.setCategoriesFilter({newCategory: IPlugin})
        spm.collectPlugins()
        for categoryName in previousCategories:
            self.assertRaises(KeyError, spm.getPluginsOfCategory, categoryName)
        self.assertTrue(len(spm.getPluginsOfCategory(newCategory)) >= 1)
コード例 #19
0
	def testChangingCategoriesFilter(self):
		"""
		Test the effect of setting a new category filer.
		"""
		spm = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# load the plugins that may be found
		spm.collectPlugins()
		newCategory = "Mouf"
		# Pre-requisite for the test
		previousCategories = spm.getCategories()
		self.assertTrue(len(previousCategories) >= 1)
		self.assertTrue(newCategory not in previousCategories)
		# change the category and see what's happening
		spm.setCategoriesFilter({newCategory: IPlugin})
		spm.collectPlugins()
		for categoryName in previousCategories:
			self.assertRaises(KeyError, spm.getPluginsOfCategory, categoryName)
		self.assertTrue(len(spm.getPluginsOfCategory(newCategory)) >= 1)
コード例 #20
0
class WeaponSystem(rpyc.Service):
    '''
    RPC Services: This is the code that does the actual password cracking
    and returns the results to orbital control.  Currently only supports
    cracking using rainbow tables (RCrackPy)
    '''

    is_initialized = False
    mutex = Lock()
    is_busy = False
    job_id = None

    def initialize(self):
        ''' Initializes variables, this should only be called once '''
        logging.info("Weapon system initializing ...")
        self.plugin_manager = PluginManager()
        self.plugin_manager.setPluginPlaces(["plugins/"])
        self.plugin_manager.setCategoriesFilter(FILTERS)
        self.plugin_manager.collectPlugins()
        self.plugins = {} 
        logging.info(
            "Loaded %d plugin(s)" % len(self.plugin_manager.getAllPlugins())
        )
        self.__cpu__()
        logging.info("Weapon system online, good hunting.")

    @atomic
    def on_connect(self):
        ''' Called when successfully connected '''
        if not self.is_initialized:
            self.initialize()
            self.is_initialized = True
        logging.info("Uplink to orbital control active")

    def on_disconnect(self):
        ''' Called if the connection is lost/disconnected '''
        logging.info("Disconnected from orbital command server.")

    def __cpu__(self):
        ''' Detects the number of CPU cores on a system (including virtual cores) '''
        if cpu_count is not None:
            try:
                self.cpu_cores = cpu_count()
                logging.info("Detected %d CPU core(s)" % self.cpu_cores)
            except NotImplementedError:
                logging.error("Could not detect number of processors; assuming 1")
                self.cpu_cores = 1
        else:
            try:
                self.cpu_cores = int(sysconf("SC_NPROCESSORS_CONF"))
                logging.info("Detected %d CPU core(s)" % self.cpu_cores)
            except ValueError:
                logging.error("Could not detect number of processors; assuming 1")
                self.cpu_cores = 1

    ############################ [ EXPOSED METHODS ] ############################
    @atomic
    def exposed_crack(self, plugin_name, job_id, hashes, **kwargs):
        ''' Exposes plugins calls '''
        assert plugin_name in self.plugins
        self.is_busy = True
        self.job_id = job_id
        self.plugin_manager.activatePluginByName(plugin_name)
        plugin = self.plugin_manager.getPluginByName(plugin_name)
        results = plugin.execute(hashes, **kwargs)
        self.plugin_manager.deactivatePluginByName(plugin_name)
        self.job_id = None
        self.is_busy = False
        return results

    def exposed_get_plugin_names(self):
        ''' Returns what algorithms can be cracked '''
        logging.info("Method called: exposed_get_capabilities")
        plugins = self.plugin_manager.getAllPlugins()
        return [plugin.name for plugin in plugins]

    def exposed_get_categories(self):
        ''' Return categories for which we have plugins '''
        categories = []
        for category in self.plugin_manager.getCategories():
            if 0 < len(self.plugin_manager.getPluginsOfCategory(category)):
                categories.append(category)
        return categories

    def exposed_get_category_plugins(self, category):
        ''' Get plugin names for a category '''
        plugins = self.plugin_manager.getPluginsOfCategory(category)
        return [plugin.name for plugin in plugins]

    def exposed_get_plugin_details(self, category, plugin_name):
        ''' Get plugin based on name details '''
        plugin = self.plugin_manager.getPluginByName(plugin_name, category)
        info = {'name': plugin.name}
        info['author'] = plugin.details.get('Documentation', 'author')
        info['website'] = plugin.details.get('Documentation', 'website')
        info['version'] = plugin.details.get('Documentation', 'version')
        info['description'] = plugin.details.get('Documentation', 'description')
        info['copyright'] = plugin.details.get('Documentation', 'copyright')
        info['precomputation'] = plugin.details.getboolean('Core', 'precomputation')
        return info

    def exposed_ping(self):
        ''' Returns a pong message '''
        return "PONG"

    def exposed_is_busy(self):
        ''' Returns True/False if the current system is busy (thread safe) '''
        return self.is_busy

    def exposed_current_job_id(self):
        ''' Returns the current job id (thread safe) '''
        return self.job_id

    def exposed_cpu_count(self):
        ''' Returns the number of detected cpu cores '''
        return self.cpu_cores
コード例 #21
0
 def test_init_with_category_filter(self):
     pm = PluginManager(categories_filter={"Mouf": IPlugin})
     self.assertEqual(["Mouf"], pm.getCategories())
     self.assertTrue(isinstance(pm.getPluginLocator(), PluginFileLocator))
コード例 #22
0
 def test_init_with_plugin_info_ext(self):
     pm = PluginManager(plugin_info_ext="bla")
     self.assertEqual(["Default"], pm.getCategories())
     self.assertTrue(isinstance(pm.getPluginLocator(), PluginFileLocator))
コード例 #23
0
ファイル: Plugins.py プロジェクト: 00mjk/sitefab
class Plugins():
    """
    Class responsible to manage the plugins

    """

    categories = [
        [
            "SitePreparsing", SitePreparsing,
            "Site wide plugins that execute before the parsing start."
        ],
        [
            "SiteProcessor", SiteProcessor,
            "Plugins that process the whole site once after parsing."
        ],
        [
            "SiteRendering", SiteRendering,
            "Plugins that render additional pages after the rendering."
        ],
        [
            "PostProcessor", PostProcessor,
            "Plugins that process each post after they are parsed"
        ],
        [
            "CollectionProcessor", CollectionProcessor,
            "Plugins that process each collection after posts are parsed"
        ],
        [
            "TemplateFilter", TemplateFilter,
            "Plugins that define jinja2 filters to be used in templates"
        ],
    ]

    # for plugin info structure
    PLUGIN_CAT = 0
    PLUGIN_NAME = 1
    PLUGIN_DESC = 2
    PLUGIN_ENABLE = 3
    PLUGIN_MODULE_NAME = 4
    PLUGIN_VERSION = 5

    def __init__(self, plugin_directories, debug_log_fname, plugins_config):
        "Load plugins"

        categories_filter = {}
        for cat in self.categories:
            categories_filter[cat[0]] = cat[1]

        # single or multi-directory handling
        if not isinstance(plugin_directories, list):
            plugin_directories = [plugin_directories]

        self.plugins = PluginManager(plugin_info_ext='sitefab-plugin',
                                     categories_filter=categories_filter)
        self.plugins.setPluginPlaces(plugin_directories)

        self.plugins.locatePlugins()
        self.plugins.loadPlugins()

        self.plugins_config = plugins_config

        # List of enabled plugins
        self.plugins_enabled = {}
        for pl in self.get_plugins_info():
            if pl[self.PLUGIN_ENABLE]:
                self.plugins_enabled[pl[self.PLUGIN_MODULE_NAME]] = 1

        # list of plugins already executed. Used for dependencies tracking
        # across stages
        self.plugins_executed = {}

        # FIXME: make sure it is working
        # logging.basicConfig(filename=debug_log_fname, level=logging.DEBUG)

    def get_plugins(self, category=None):
        """Return the list of plugins

        :param str category: restrict to plugins of a given category

        :rtype: list(iPlugin)
        :return: list of plugins
        """
        if category:
            return self.plugins.getPluginsOfCategory(category)
        else:
            return self.plugins.getAllPlugins()

    def get_num_plugins(self, category=None):
        """ Return the number of plugins available.

        :param str category: restrict to plugins of given category

        :rtype: int
        :return: number of plugins
        """
        plugins = self.get_plugins(category)
        return len(plugins)

    def get_plugin_dir(self, plugin):
        """ Return the directory where the plugin is stored

        :param iPlugin plugin: the plugin requested

        :rtype: str
        :return: the module name
        """

        module_path = Path(plugin.details.get("Core", "module"))
        return module_path.parent

    def get_plugin_default_configuration_filename(self, plugin):
        """ Return the path to the plugin default configuration filename
        """
        try:
            fname = plugin.details.get("Configuration", "Filename")
        except:  # noqa
            return ""
        fname = fname.replace('"', '')
        path = self.get_plugin_dir(plugin)
        return path / fname

    def get_plugin_documentation_filename(self, plugin):
        """ Return the path to the plugin documentation
        """
        try:
            fname = plugin.details.get("Documentation", "Filename")
        except:  # noqa
            return ""
        path = self.get_plugin_dir(plugin)
        return path / fname

    def get_plugin_class_name(self, plugin):
        """ Return the class of a given plugin

        :param iPlugin plugin: the plugin requested

        :rtype: str
        :return: the module classname
        """
        return plugin.categories[0]

    def get_plugin_module_name(self, plugin):
        """ Return the module name of a given plugin

        :param iPlugin plugin: the plugin requested

        :rtype: str
        :return: the module name
        """
        module_path = plugin.details.get("Core", "module")
        path, filename = os.path.split(module_path)
        return filename

    def get_plugin_config(self, plugin):
        """ Return the configuration of a given plugin

        :param iPlugin plugin: the plugin requested

        :rtype: dict
        :return: plugin configuration
        """
        module_name = self.get_plugin_module_name(plugin)
        class_name = self.get_plugin_class_name(plugin)
        try:
            config = self.plugins_config[class_name][module_name]
        except:  # noqa
            config = {}
        return config

    def get_plugin_dependencies(self, plugin):
        """ Return the dependency of a given plugin

        :param iPlugin plugin: the plugin requested

        :rtype: list
        :return: list of plugins name the plugin depend on
        """

        # No dependencies
        if not plugin.details.has_option("Core", "Dependencies"):
            return set()

        dependencies = set()
        st = plugin.details.get("Core", "Dependencies")
        if "," in st:
            elts = st.split(",")
            for elt in elts:
                dependencies.add(elt.strip())
        else:
            dependencies.add(st)
        return dependencies

    def is_plugin_enabled(self, plugin):
        config = self.get_plugin_config(plugin)
        if config.get('enable'):
            return True
        else:
            return False

    def get_plugins_info(self, category=None):
        """Return the list of plugins available with their type

        :param str category: restrict to plugins of a given category.

        :rtype: list(str)
        :return: list of plugins name
        """
        pl = []
        if category:
            categories = [category]
        else:
            categories = self.plugins.getCategories()
        for cat in categories:
            for plugin in self.plugins.getPluginsOfCategory(cat):
                enabled = self.is_plugin_enabled(plugin)
                module_name = self.get_plugin_module_name(plugin)
                try:
                    version = plugin.version
                except:  # noqa
                    version = "NA"

                s = [
                    cat, plugin.name, plugin.description, enabled, module_name,
                    version
                ]
                pl.append(s)
        return pl

    def display_execution_results(self, results, site):
        """ Display execution summary
        """
        cprint("|-Execution result", "magenta")
        table_data = [['name', 'ok', 'skipped', 'errors']]
        count = 0
        for result in results:
            row = []
            plugin_name, stats = result

            # plugin name
            c = "cyan"
            if count % 2:
                c = "blue"
            row.append(colored(plugin_name, c))

            # ok
            if stats[site.OK]:
                if stats[site.OK] == 1:
                    val = 'v'
                else:
                    val = stats[site.OK]
                row.append(colored(val, 'green'))
            else:
                row.append(' ')

            # warning
            if stats[site.SKIPPED]:
                row.append(colored(stats[site.SKIPPED], "yellow"))
            else:
                row.append(' ')

            # error
            if stats[site.ERROR]:
                if stats[site.ERROR] == 1:
                    val = 'x'
                else:
                    val = stats[site.ERROR]
                row.append(colored(val, "red"))
            else:
                row.append(' ')

            table_data.append(row)
            count += 1

        print(SingleTable(table_data).table)

    def run_plugins(self, items, plugin_class, unit, site):
        """Execute a set of plugins on a given list of items

        :param list items: list of items to process
        :param str plugin_type: the plugin_class to use
        :param str unit: the unit to use in the display
        :param SiteFab site: pointer to the site object to be passed
        to the plugins

        :rtype: dict(dict(list))
        :return: plugins execution statistics
        """

        # dependencies map
        dependencie_map = {}

        # used to get back from the module name to the plugin
        module_name_to_plugin = {}

        plugins = self.plugins.getPluginsOfCategory(plugin_class)

        # collecting plugins that are to be executed.
        for plugin in plugins:
            if self.is_plugin_enabled(plugin):
                module_name = self.get_plugin_module_name(plugin)
                module_name_to_plugin[module_name] = plugin

        # dependencies computation.
        # Due to  potential dependencies on plugins from previous stage
        # this must be computed after collecting which
        # plugins were executed.
        for plugin in module_name_to_plugin.values():
            all_dependencies = self.get_plugin_dependencies(plugin)
            dependencies = set()  # topological sort requires use of set
            module_name = self.get_plugin_module_name(plugin)

            for dep_module_name in all_dependencies:
                if dep_module_name not in self.plugins_enabled:
                    utils.error("Plugin:%s can't be executed because\
                                plugin %s is not enable" %
                                (module_name, dep_module_name))

                # only add to the dependencies map the plugins
                # that are from the same stage
                if dep_module_name in module_name_to_plugin:
                    dependencies.add(dep_module_name)
                else:
                    # check if already executed
                    if dep_module_name not in self.plugins_executed:
                        utils.error("Plugin:%s can't be executed because\
                                    plugin %s was not executed in previous\
                                    stage" % (module_name, dep_module_name))

            dependencie_map[module_name] = dependencies

        # print dependencie_map

        # Topological sorting
        try:
            plugins_to_process = toposort_flatten(dependencie_map)
        except Exception as e:
            utils.error("Circular dependencies between plugins.\
                Can't execute plugins:%s" % e)

        s = "|-%s plugins" % (unit.strip().capitalize())
        desc = colored(s, "magenta")
        results = []
        for module_name in tqdm(plugins_to_process,
                                unit=' plugin',
                                desc=desc,
                                leave=True):
            if module_name in module_name_to_plugin:
                plugin = module_name_to_plugin[module_name]
            else:
                raise Exception("The following plugin module name listed in\
                    dependencies don't exist % s " % module_name)

            pclass = plugin_class.lower()
            filename = "%s.%s.html" % (pclass, module_name)
            log_id = site.logger.create_log(pclass, plugin.name, filename)

            plugin_results = utils.dict_to_objdict({
                site.OK: 0,
                site.SKIPPED: 0,
                site.ERROR: 0
            })

            config = self.get_plugin_config(plugin)

            for item in tqdm(items, unit=unit, desc=plugin.name, leave=False):
                result = plugin.plugin_object.process(item, site, config)
                plugin_results[result[0]] += 1

                severity = result[0]
                name = result[1]
                details = result[2]
                site.logger.record_event(log_id, name, severity, details)

            self.plugins_executed[module_name] = True
            results.append([plugin.name, plugin_results])
            site.logger.write_log(log_id)
        return results

    def get_template_filters(self):
        """Load template filters and return a dictionary list

        Return:
            dict: jinja filter functions
        """
        template_filters = {}

        filters = self.plugins.getPluginsOfCategory("TemplateFilter")

        for flt in filters:
            filter_name = self.get_plugin_module_name(flt)
            template_filters[filter_name] = flt.plugin_object.myfilter

        return template_filters
コード例 #24
0
 def test_default_init(self):
     pm = PluginManager()
     self.assertEqual(["Default"], pm.getCategories())
     self.assertTrue(isinstance(pm.getPluginLocator(), PluginFileLocator))
コード例 #25
0
def main(args: List[AnyStr] = None) -> int:
    """
    prepare and start application

    the main method is responsible for setting up the environment,
    i.e. to load translations, set a logger, parse the command line arguments,
    load configuration files and start the application.

    :param args: command line arguments; default: None
    :type args: List of strings
    """
    if not args:
        args = sys.argv

    script_name = os.path.basename(sys.argv[0])
    application = AppDirs(os.path.splitext(script_name)[0],
                          appauthor=__author__,
                          version=__version__,
                          roaming=True)
    logging_path = application.user_data_dir
    config_path = application.user_config_dir

    # set locale
    locale.setlocale(locale.LC_ALL, '')
    _locale = locale.getlocale(locale.LC_ALL)[0]
    locale_path = pkg_resources.resource_filename("servertools", "data/i18n")

    translate = gettext.translation("servertools",
                                    localedir=locale_path,
                                    languages=[locale.getlocale()[0], 'en'])
    translate.install()

    if '_' not in globals():
        _ = unicode

    # setup logging
    handlers = _log_default_handler(proc=script_name, log_dir=logging_path)
    logging.basicConfig(level=4, format="%(message)s", handlers=handlers)

    logger = logging.getLogger("{}_logger".format(
        os.path.splitext(script_name)[0]))
    logger.setLevel(logging.DEBUG)

    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.WARNING)
    stream_handler.setFormatter(logging.Formatter("%(message)s"))
    logger.addHandler(stream_handler)

    # setup argument parser
    parser = ArgumentParser(prog=script_name)
    verbosity_parsergroup = parser.add_mutually_exclusive_group()
    verbosity_parsergroup.add_argument("-v",
                                       dest='verbosity',
                                       action="count",
                                       help=_("increase verbosity"),
                                       default=0)
    verbosity_parsergroup.add_argument(
        "--silent",
        action="store_true",
        help=_("silent (no output to terminal)"))
    parser.add_argument("--version",
                        action="version",
                        help=_("print version and exit"))
    parser.add_argument("--log-file",
                        metavar='FILEPATH',
                        action="store",
                        help=_("overwrite path to log file"))

    command_parsers = parser.add_subparsers(help="commands")
    identify_parser = command_parsers.add_parser("identify",
                                                 add_help=False,
                                                 parents=[parser])

    # load plugins for different server types
    plugins_directories = [
        pkg_resources.resource_filename("servertools", "plugins"),
        os.path.join(application.user_data_dir, 'plugins'),
        os.path.expanduser(
            os.path.normpath(
                '~/.{appname}/plugins'.format(appname=application.appname)))
    ]
    sys.path.extend(plugins_directories)
    plugin_manager = PluginManager(directories_list=plugins_directories,
                                   plugin_info_ext='plugin')
    plugin_manager.setCategoriesFilter({
        "Server": Server,
    })
    plugin_manager.locatePlugins()
    plugin_manager.collectPlugins()

    # plugins to identify servers and fix problems that might happen on them
    plugins = plugin_manager.getPluginsOfCategory(
        'Server')  # type: List[PluginInfo]

    # choices for the command line flag `--look-for`
    server_choices = []  # type: List[AnyStr]
    # set valid values for --look-for from installed plugins
    for plugin in plugins:
        commandline_argument = plugin.name.lower().replace('server',
                                                           '').strip().replace(
                                                               ' ', '-')
        if len(commandline_argument) > 0:
            server_choices.append(commandline_argument)
        else:
            raise ValueError(
                _("Plugin {name} doesn't have a valid name!").format(
                    name=plugin.name))

    identify_parser.add_argument("--look-for",
                                 metavar="SERVER",
                                 dest="look_for",
                                 help=_("look for a specific server"),
                                 choices=server_choices,
                                 default='')
    identify_parser.set_defaults(name="identify")

    # fix_parser = command_parsers.add_parser('fix', help=_('apply fixes for a server'))
    # parse arguments
    args = parser.parse_args(args[1:])

    # handle verbosity
    verbosity = max(0, min(3, args.verbosity))
    if args.silent:
        verbosity = -1

    logging_level = {
        -1: logging.CRITICAL,  # 50
        0: logging.WARNING,  # 30
        1: logging.INFO,  # 20
        2: logging.INFO,  # 20
        3: logging.DEBUG  # 10
    }.get(verbosity, logging.WARNING)
    stream_handler.setLevel(logging_level)
    verbose = logger.info if verbosity > 1 else logger.debug

    # start application
    logger.debug(
        _("{program} started at {started_at:%X} on Python {py_version} ({architecture})"
          ).format(program=script_name,
                   started_at=datetime.now(),
                   py_version=platform.python_version(),
                   architecture=platform.architecture()[0]))
    logger.debug(
        _("Verbosity Level at {verbosity}").format(verbosity=verbosity))

    plugins_information = {}
    for category in plugin_manager.getCategories():
        plugins_information[category] = list()
        for plugin in plugin_manager.getPluginsOfCategory(category):
            plugins_information[category].append({
                'name': plugin.name,
                'author': plugin.author
            })

    # if verbosity > 1:
    logger.info(_("Save logs to {path}").format(path=logging_path))
    logger.info(_("Load configurations from {path}").format(path=config_path))
    logger.info(
        _('Look for plugins in:\n\t{path}').format(
            path=',\n\t'.join(plugins_directories)))
    verbose(
        _('Include {amount} Plugin Categories.').format(
            amount=len(plugin_manager.getCategories())))
    logger.debug(', '.join(plugin_manager.getCategories()))
    verbose(
        _('{amount} Plugin(s) loaded.').format(
            amount=len(plugins_information.keys())))

    for category in plugins_information:
        logger.debug('[{}]'.format(category))
        for cat in plugins_information[category]:
            logger.debug(
                _('\t{name} (by {author})').format(name=cat['name'],
                                                   author=cat['author']))
        logger.debug('')

    for plugin in plugins:
        logger.debug(_("Try to identify {name}").format(name=plugin.name))
        command = plugin.name.lower().replace('server',
                                              '').strip().replace(' ', '-'),
        if args.look_for == command and plugin.plugin_object.identify():
            logger.debug(
                _("Successfully identified {name}").format(name=plugin.name))
            print("{} - {}".format(plugin.details.get('Server Info', 'Host'),
                                   plugin.details.get('Server Info',
                                                      'Slogan')))
            break
    else:
        print(
            _('Not {}').format(args.look_for)
            if len(args.look_for) > 0 else _('Unknown platform'))
        return 1
    logger.debug("-" * 80)
    return 0
コード例 #26
0
ファイル: config.py プロジェクト: invenia/shepherd
class Config(object):
    """
    The :class:`Config <Config>` is responsible for managing the
    plugins and executing given tasks.
    """
    _configs = []
    logging_verbosity = 0

    def __init__(self, settings, name):
        """Summary

        Args:
            settings (dict): the dictionary of settings
            name (str): the config name
        """
        assert settings is not None
        assert name is not None

        self._name = name
        self._settings = settings
        self._inspect_analyzer = None
        self._default_analyzer = None
        self._categories = None
        self._paths = _BUILTIN_PATHS
        self._plugins = None
        self._stacks = []

        validate_config(settings)
        if Config.logging_verbosity < settings['verbosity']:
            configure_logging(settings['verbosity'])
            Config.logging_verbosity = settings['verbosity']
            logger.info(
                'Increased logging verbosity from %s to %s with the new config...',
                Config.logging_verbosity,
                settings['verbosity']
            )

        self._configure_plugins()

    def _configure_plugins(self):
        """
        Handles initialization of the
        :class:`Config <Config>`.  This method shouldn't be called
        outside of this class.
        """
        logger.debug('Configuring Config')

        # Setup the locators
        # Inspection analyzer, mostly for builtin plugins
        # (resources, tasks, etc)
        self._inspect_analyzer = PluginFileAnalyzerInspection(
            'inspector',
            _BUILTIN_PATHS
        )
        # The default analyzer for any extension paths that we don't trust.
        self._default_analyzer = PluginFileAnalyzerWithInfoFile(
            'default',
            extensions='plugin'
        )
        # The order of the analyzers could matter.
        self._locator = PluginFileLocator(
            analyzers=[
                self._inspect_analyzer,
                self._default_analyzer,
            ]
        )

        # Create the categories filter dict
        self._categories = {
            "Resource": Resource,
            "Action": Action,
            "Storage": Storage,
            "Parser": Parser,
        }

        # Setup the search paths
        if self._settings and "extension_paths" in self._settings:
            self._paths.extend(self._settings["extension_paths"])

        # Actually create the PluginManager
        self._plugins = PluginManager(
            categories_filter=self._categories,
            directories_list=self._paths,
            plugin_locator=self._locator
        )

        # Collect the plugins
        self._plugins.collectPlugins()

    @property
    def name(self):
        return self._name

    @property
    def settings(self):
        return self._settings

    @classmethod
    def make(cls, settings=None, name=""):
        """
        When first setting up the Config you should call this
        class method.

        Args:
            settings (dict, optional): desire settings values overriding the defaults.
            name (str, optional): the name of the config

        Returns: the created config obj
        """
        logger.debug('Creating Config named "%s"', name)
        config_settings = _DEFAULT_SETTINGS
        if settings:
            config_settings.update(settings)

        assert config_settings is not None
        new_config = Config(config_settings, name)
        for index, config in enumerate(cls._configs):
            if config.name == name:
                logger.warn('Recreating Config named %s', name)
                cls._configs[index] = new_config
                break
        else:
            cls._configs.append(new_config)

        return new_config

    @classmethod
    def make_from_file(cls, filename, name=""):
        """
        Loads the settings dict from a file and passes it to Config.make.

        Args:
            filename (str): name of the file to load
            name (str, optional): the name of the config

        Returns:
            Config: the created config obj
        """
        settings = anyconfig.load(filename, safe=True)
        return cls.make(settings=settings, name=name)

    @classmethod
    def get(cls, name=""):
        """
        Use this to access your desired Config.

        Args:
            name (str, optional): the unique name of the config you
                want returned.

        Returns: the config obj

        Raises:
            KeyError: if a config by that name does't exist.
        """
        logger.debug('Retrieving Config named "%s"', name)

        for config in cls._configs:
            if config.name == name:
                return config
        else:
            raise KeyError('No config with the name {} exists'.format(name))

    def get_plugins(self, category_name=None, plugin_name=None):
        """
        get_plugins returns a deepcopy of all the plugins fitting
        the search criteria.  While this isn't very memory efficient
        our plugins should be small and few between enough that it'll be
        worth getting independent copies of them.  For example we will likely
        want to work with multiple copies of the Same Resource plugin.

        Args:
            category_name (str, optional): a category to search for plugins in.
            plugin_name (str, optional): the name of the plugin to look for.

        Returns:
            list: of the plugins that match the criteria.
        """
        results = []

        if category_name and plugin_name:
            plugin_info = self._plugins.getPluginByName(
                plugin_name,
                category=category_name
            )

            if plugin_info:
                results.append(plugin_info.plugin_object.__class__())

        elif category_name and not plugin_name:
            plugin_infos = self._plugins.getPluginsOfCategory(category_name)

            for plugin_info in plugin_infos:
                results.append(plugin_info.plugin_object.__class__())

        elif plugin_name and not category_name:
            for category in self._plugins.getCategories():
                plugin_info = self._plugins.getPluginByName(
                    plugin_name,
                    category=category
                )

                if plugin_info:
                    results.append(plugin_info.plugin_object.__class__())

        elif not category_name and not plugin_name:
            plugin_infos = self._plugins.getAllPlugins()

            for plugin_info in plugin_infos:
                results.append(plugin_info.plugin_object.__class__())

        return results
コード例 #27
0
	def test_default_init(self):
		pm = PluginManager()
		self.assertEqual(["Default"],pm.getCategories())
		self.assertTrue(isinstance(pm.getPluginLocator(),PluginFileLocator))
コード例 #28
0
class WeaponSystem(rpyc.Service):
    '''
    RPC Services: This is the code that does the actual password cracking
    and returns the results to orbital control.  Currently only supports
    cracking using rainbow tables (RCrackPy)
    '''

    is_initialized = False
    mutex = Lock()
    is_busy = False
    job_id = None

    def initialize(self):
        ''' Initializes variables, this should only be called once '''
        logging.info("Weapon system initializing ...")
        self.plugin_manager = PluginManager()
        self.plugin_manager.setPluginPlaces(["plugins/"])
        self.plugin_manager.setCategoriesFilter(FILTERS)
        self.plugin_manager.collectPlugins()
        self.plugins = {}
        logging.info("Loaded %d plugin(s)" %
                     len(self.plugin_manager.getAllPlugins()))
        self.__cpu__()
        logging.info("Weapon system online, good hunting.")

    @atomic
    def on_connect(self):
        ''' Called when successfully connected '''
        if not self.is_initialized:
            self.initialize()
            self.is_initialized = True
        logging.info("Uplink to orbital control active")

    def on_disconnect(self):
        ''' Called if the connection is lost/disconnected '''
        logging.info("Disconnected from orbital command server.")

    def __cpu__(self):
        ''' Detects the number of CPU cores on a system (including virtual cores) '''
        if cpu_count is not None:
            try:
                self.cpu_cores = cpu_count()
                logging.info("Detected %d CPU core(s)" % self.cpu_cores)
            except NotImplementedError:
                logging.error(
                    "Could not detect number of processors; assuming 1")
                self.cpu_cores = 1
        else:
            try:
                self.cpu_cores = int(sysconf("SC_NPROCESSORS_CONF"))
                logging.info("Detected %d CPU core(s)" % self.cpu_cores)
            except ValueError:
                logging.error(
                    "Could not detect number of processors; assuming 1")
                self.cpu_cores = 1

    ############################ [ EXPOSED METHODS ] ############################
    @atomic
    def exposed_crack(self, plugin_name, job_id, hashes, **kwargs):
        ''' Exposes plugins calls '''
        assert plugin_name in self.plugins
        self.is_busy = True
        self.job_id = job_id
        self.plugin_manager.activatePluginByName(plugin_name)
        plugin = self.plugin_manager.getPluginByName(plugin_name)
        results = plugin.execute(hashes, **kwargs)
        self.plugin_manager.deactivatePluginByName(plugin_name)
        self.job_id = None
        self.is_busy = False
        return results

    def exposed_get_plugin_names(self):
        ''' Returns what algorithms can be cracked '''
        logging.info("Method called: exposed_get_capabilities")
        plugins = self.plugin_manager.getAllPlugins()
        return [plugin.name for plugin in plugins]

    def exposed_get_categories(self):
        ''' Return categories for which we have plugins '''
        categories = []
        for category in self.plugin_manager.getCategories():
            if 0 < len(self.plugin_manager.getPluginsOfCategory(category)):
                categories.append(category)
        return categories

    def exposed_get_category_plugins(self, category):
        ''' Get plugin names for a category '''
        plugins = self.plugin_manager.getPluginsOfCategory(category)
        return [plugin.name for plugin in plugins]

    def exposed_get_plugin_details(self, category, plugin_name):
        ''' Get plugin based on name details '''
        plugin = self.plugin_manager.getPluginByName(plugin_name, category)
        info = {'name': plugin.name}
        info['author'] = plugin.details.get('Documentation', 'author')
        info['website'] = plugin.details.get('Documentation', 'website')
        info['version'] = plugin.details.get('Documentation', 'version')
        info['description'] = plugin.details.get('Documentation',
                                                 'description')
        info['copyright'] = plugin.details.get('Documentation', 'copyright')
        info['precomputation'] = plugin.details.getboolean(
            'Core', 'precomputation')
        return info

    def exposed_ping(self):
        ''' Returns a pong message '''
        return "PONG"

    def exposed_is_busy(self):
        ''' Returns True/False if the current system is busy (thread safe) '''
        return self.is_busy

    def exposed_current_job_id(self):
        ''' Returns the current job id (thread safe) '''
        return self.job_id

    def exposed_cpu_count(self):
        ''' Returns the number of detected cpu cores '''
        return self.cpu_cores
コード例 #29
0
class SimpleTestsCase(unittest.TestCase):
	"""
	Test the correct loading of a simple plugin as well as basic
	commands.
	"""
	
	def setUp(self):
		"""
		init
		"""
		# create the plugin manager
		self.simplePluginManager = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# load the plugins that may be found
		self.simplePluginManager.collectPlugins()
		# Will be used later
		self.plugin_info = None

	def plugin_loading_check(self):
		"""
		Test if the correct plugin has been loaded.
		"""
		if self.plugin_info is None:
			# check nb of categories
			self.assertEqual(len(self.simplePluginManager.getCategories()),1)
			sole_category = self.simplePluginManager.getCategories()[0]
			# check the number of plugins
			self.assertEqual(len(self.simplePluginManager.getPluginsOfCategory(sole_category)),1)
			self.plugin_info = self.simplePluginManager.getPluginsOfCategory(sole_category)[0]
			# test that the name of the plugin has been correctly defined
			self.assertEqual(self.plugin_info.name,"Simple Plugin")
			self.assertEqual(sole_category,self.plugin_info.category)
		else:
			self.assert_(True)

	def testLoaded(self):
		"""
		Test if the correct plugin has been loaded.
		"""
		self.plugin_loading_check()

	def testGetAll(self):
		"""
		Test if the correct plugin has been loaded.
		"""
		self.plugin_loading_check()
		self.assertEqual(len(self.simplePluginManager.getAllPlugins()),1)
		self.assertEqual(self.simplePluginManager.getAllPlugins()[0],self.plugin_info)
		

	def testActivationAndDeactivation(self):
		"""
		Test if the activation procedure works.
		"""
		self.plugin_loading_check()
		self.assert_(not self.plugin_info.plugin_object.is_activated)
		self.simplePluginManager.activatePluginByName(self.plugin_info.name,
													  self.plugin_info.category)
		self.assert_(self.plugin_info.plugin_object.is_activated)
		self.simplePluginManager.deactivatePluginByName(self.plugin_info.name,
														self.plugin_info.category)
		self.assert_(not self.plugin_info.plugin_object.is_activated)
コード例 #30
0
	def test_init_with_category_filter(self):
		pm = PluginManager(categories_filter={"Mouf": IPlugin})
		self.assertEqual(["Mouf"],pm.getCategories())
		self.assertTrue(isinstance(pm.getPluginLocator(),PluginFileLocator))
コード例 #31
0
	def test_init_with_plugin_info_ext(self):
		pm = PluginManager(plugin_info_ext="bla")
		self.assertEqual(["Default"],pm.getCategories())
		self.assertTrue(isinstance(pm.getPluginLocator(),PluginFileLocator))
コード例 #32
0
	def test_init_with_plugin_locator(self):
		class SpecificLocator(IPluginLocator):
			pass
		pm = PluginManager(plugin_locator=SpecificLocator())
		self.assertEqual(["Default"],pm.getCategories())
		self.assertTrue(isinstance(pm.getPluginLocator(),SpecificLocator))
コード例 #33
0
ファイル: test_SimplePlugin.py プロジェクト: sueastside/yapsy
class SimpleTestsCase(unittest.TestCase):
    """
	Test the correct loading of a simple plugin as well as basic
	commands.
	"""
    def setUp(self):
        """
		init
		"""
        # create the plugin manager
        self.simplePluginManager = PluginManager(directories_list=[
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")
        ])
        # load the plugins that may be found
        self.simplePluginManager.collectPlugins()
        # Will be used later
        self.plugin_info = None

    def plugin_loading_check(self):
        """
		Test if the correct plugin has been loaded.
		"""
        if self.plugin_info is None:
            # check nb of categories
            self.assertEqual(len(self.simplePluginManager.getCategories()), 1)
            sole_category = self.simplePluginManager.getCategories()[0]
            # check the number of plugins
            self.assertEqual(
                len(
                    self.simplePluginManager.getPluginsOfCategory(
                        sole_category)), 1)
            self.plugin_info = self.simplePluginManager.getPluginsOfCategory(
                sole_category)[0]
            # test that the name of the plugin has been correctly defined
            self.assertEqual(self.plugin_info.name, "Simple Plugin")
            self.assertEqual(sole_category, self.plugin_info.category)
        else:
            self.assert_(True)

    def testLoaded(self):
        """
		Test if the correct plugin has been loaded.
		"""
        self.plugin_loading_check()

    def testGetAll(self):
        """
		Test if the correct plugin has been loaded.
		"""
        self.plugin_loading_check()
        self.assertEqual(len(self.simplePluginManager.getAllPlugins()), 1)
        self.assertEqual(self.simplePluginManager.getAllPlugins()[0],
                         self.plugin_info)

    def testActivationAndDeactivation(self):
        """
		Test if the activation procedure works.
		"""
        self.plugin_loading_check()
        self.assert_(not self.plugin_info.plugin_object.is_activated)
        self.simplePluginManager.activatePluginByName(
            self.plugin_info.name, self.plugin_info.category)
        self.assert_(self.plugin_info.plugin_object.is_activated)
        self.simplePluginManager.deactivatePluginByName(
            self.plugin_info.name, self.plugin_info.category)
        self.assert_(not self.plugin_info.plugin_object.is_activated)