def read_config(self):
     config = ConfigParser()
     try:
         with open(self.config_file, "r") as cfg:
             config.readfp(cfg)
     except IOError, e:
         self.print_shell("Error: config_file not found", e)
class TestFileServerLLAMethods(EvaluateTestResults):
    """
    Tests FileServerLLA Methods
    """

    @classmethod
    def setUp(self):
        """
        setup
        """
        self.lla = afs.lla.FileServerLLA.FileServerLLA()
        self.test_config = ConfigParser()
        self.test_config.read(afs.CONFIG.setup)
        self.FS = afs.model.FileServer.FileServer()
        self.FS.servernames = [self.test_config.get("FileServerLLA", "FS")]
        self.Part = self.test_config.get("FileServerLLA", "Part")
        self.allParts = self.test_config.get("FileServerLLA", "allParts")
        return

    def test_get_volume_list(self):
        res = self.lla.get_volume_list(self.FS, part=self.Part)
        self.eval_get_volume_list(res)
        return

    def test_get_volume_id_list(self):
        res = self.lla.get_volume_id_list(self.FS, part=self.Part)
        self.eval_get_volume_id_list(res)
        return

    def test_get_partitions(self):
        res = self.lla.get_partitions(self.FS)
        self.eval_get_volume_list(res)
        return
def test_umit_conf_content(filename):
    parser = ConfigParser()
    parser.read(filename)

    # Paths section
    section = "paths"
    assert get_or_false(parser, section, "nmap_command_path")
Example #4
0
def parse_config_file(config_file):
    """
    We have a single configuration file which may contain a risk section and
    a hazard section. This input file must be in the ConfigParser format
    defined at: http://docs.python.org/library/configparser.html.

    There may be a general section which may define configuration includes in
    the format of "sectionname_include = someconfigname.gem". These too must be
    in the ConfigParser format.
    """

    parser = ConfigParser()
    parser.read(config_file)

    params = {}
    sections = []
    for section in parser.sections():
        for key, value in parser.items(section):
            key = key.upper()
            # Handle includes.
            if RE_INCLUDE.match(key):
                config_file = "%s/%s" % (os.path.dirname(config_file), value)
                new_sections, new_params = parse_config_file(config_file)
                sections.extend(new_sections)
                params.update(new_params)
            else:
                sections.append(section)
                params[key] = value
    return sections, params
Example #5
0
    def readFrom(self, path, section):
        parser = ConfigParser()
        if not parser.read(path):
            raise CarbonConfigException("Failed to read config file %s" % path)

        if not parser.has_section(section):
            return

        for key, value in parser.items(section):
            key = key.upper()

            # Detect type from defaults dict
            if key in defaults:
                valueType = type(defaults[key])
            else:
                valueType = str

            if valueType is list:
                value = [v.strip() for v in value.split(",")]

            elif valueType is bool:
                value = parser.getboolean(section, key)

            else:
                # Attempt to figure out numeric types automatically
                try:
                    value = int(value)
                except ValueError:
                    try:
                        value = float(value)
                    except ValueError:
                        pass

            self[key] = value
Example #6
0
def import_members(options):
    log("Importing members")
    pr = options.plone.portal_registration
    pm = options.plone.portal_membership
    members_ini = os.path.join(options.input_directory, "members.ini")

    CP = ConfigParser()
    CP.read([members_ini])
    get = CP.get

    count = 0
    errors = list()
    pr.addMember("dummyadmin", "dummyadmin", roles=("Member",))

    for section in CP.sections():
        username = get(section, "username")
        if options.verbose:
            log("-> %s" % username)

        # omit group accounts
        if username.startswith("group_"):
            continue

        roles = get(section, "roles").split(",") + ["Member"]

        try:
            pr.addMember(username, get(section, "password"), roles=roles)
        except Exception, e:
            errors.append(dict(username=username, error=e))
            continue
        count += 1
        member = pm.getMemberById(username)
        pm.createMemberArea(username)
        member.setMemberProperties(dict(email=get(section, "email"), fullname=get(section, "fullname")))
    def _populate_config_from_old_location(self, conf):
        if (
            "rate_limit_after_segment" in conf
            or "rate_limit_segments_per_sec" in conf
            or "max_get_time" in conf
            or "__file__" not in conf
        ):
            return

        cp = ConfigParser()
        if os.path.isdir(conf["__file__"]):
            read_conf_dir(cp, conf["__file__"])
        else:
            cp.read(conf["__file__"])

        try:
            pipe = cp.get("pipeline:main", "pipeline")
        except (NoSectionError, NoOptionError):
            return

        proxy_name = pipe.rsplit(None, 1)[-1]
        proxy_section = "app:" + proxy_name
        for setting in ("rate_limit_after_segment", "rate_limit_segments_per_sec", "max_get_time"):
            try:
                conf[setting] = cp.get(proxy_section, setting)
            except (NoSectionError, NoOptionError):
                pass
Example #8
0
    def __init__(self):
        # a list of all available modules
        # ("short_desc", "filename", "required_access_level", "long_desc")
        self.modules = [
            ("Bedrifter", "Companies.py", "comp", "Her kan du editere bedriftsdatabasen"),
            ("Brukere", "Users.py", "mail", "Legge til eller endre brukere"),
            ("MailingLists", "Sympa.py", "mail", "Administrasjon av epost-lister"),
            (
                "Virtual/Aliaser",
                "Virtual.py",
                "mail",
                "Gjøre endringer i aliases og virtuals som ikke er knyttet opp mot brukere",
            ),
        ]

        Page.__init__(self)
        self.syslog = Syslog()
        conf = ConfigParser()
        self.conf = conf
        conf.readfp(open("site.conf"))
        if conf.get("global", "database") == "mysql":
            from Mysql import Database

        self.cyrus = Cyrus(conf)
        self.db = Database(conf)
        self.allow_caching = 0
Example #9
0
def read_configuration():
    config = ConfigParser()

    # load global configuration file
    global_config = resource_path("resources", "config_global.ini")
    if os.path.isfile(global_config):
        # print 'load global configuration: %s' % global_config
        with open(global_config, "r") as f:
            config.readfp(f)

    # load further configuration files
    configs = []

    # The application may provide its own default configuration.
    provided_config = resource_path("resources", "config.ini")
    if os.path.isfile(provided_config):
        # print 'load provided configuration: %s' % custom_config
        configs.append(provided_config)

    # There may also be a configuration file next to the application binary.
    custom_config = app_path("config.ini")
    if os.path.isfile(custom_config):
        # print 'load custom configuration: %s' % custom_config
        configs.append(custom_config)

    if len(configs) > 0:
        config.read(configs)

    return config
Example #10
0
def configuration(parent_package="", top_path=None):
    from numpy.distutils.misc_util import Configuration
    from numpy.distutils.system_info import get_info, get_standard_file, BlasNotFoundError

    config = Configuration("linear_model", parent_package, top_path)

    site_cfg = ConfigParser()
    site_cfg.read(get_standard_file("site.cfg"))

    # cd fast needs CBLAS
    blas_info = get_info("blas_opt", 0)
    if (not blas_info) or (("NO_ATLAS_INFO", 1) in blas_info.get("define_macros", [])):
        cblas_libs = ["cblas"]
        blas_info.pop("libraries", None)
    else:
        cblas_libs = blas_info.pop("libraries", [])

    config.add_extension(
        "cd_fast",
        sources=["cd_fast.c"],
        libraries=cblas_libs,
        include_dirs=[join("..", "src", "cblas"), numpy.get_include(), blas_info.pop("include_dirs", [])],
        extra_compile_args=blas_info.pop("extra_compile_args", []),
        **blas_info
    )

    # add other directories
    config.add_subpackage("tests")
    config.add_subpackage("sparse")

    return config
Example #11
0
    def read_config(fn):
        '''Return a case sensitive ConfigParser by reading the file "fn"'''
        cp = ConfigParser()
        cp.optionxform = str
        cp.read(fn)

        return cp
Example #12
0
    def test_taxii(self):
        """
        Objective: Test if we can transmit data to MITRE's TAXII test server.
        Note: This actually also tests the StixTransformer since the event is parsed by the transformer
        before transmission.
        """
        config = ConfigParser()
        config_file = os.path.join(os.path.dirname(__file__), "../conpot.cfg")
        config.read(config_file)
        config.set("taxii", "enabled", True)

        test_event = {
            "remote": ("127.0.0.1", 54872),
            "data_type": "s7comm",
            "timestamp": datetime.now(),
            "session_id": "101d9884-b695-4d8b-bf24-343c7dda1b68",
            "data": {
                0: {"request": "who are you", "response": "mr. blue"},
                1: {"request": "give me apples", "response": "no way"},
            },
        }
        dom = etree.parse("conpot/templates/default.xml")
        taxiiLogger = TaxiiLogger(config, dom)
        taxii_result = taxiiLogger.log(test_event)
        # TaxiiLogger returns false if the message could not be delivered
        self.assertTrue(taxii_result)
Example #13
0
 def load_all(conf_d=None):
     """
     Load all enabled content sources.
     :param conf_d: The absolute path to a directory containing
         content source descriptor files.
     :type conf_d: str
     :return: Dictionary of: ContentSource keyed by source_id.
     :rtype: dict
     """
     sources = {}
     _dir = conf_d or ContentSource.CONF_D
     for name in os.listdir(_dir):
         if not name.endswith(".conf"):
             continue
         path = os.path.join(_dir, name)
         cfg = ConfigParser()
         cfg.read(path)
         for section in cfg.sections():
             descriptor = dict(cfg.items(section))
             source = ContentSource(section, descriptor)
             if not source.enabled:
                 continue
             if not source.is_valid():
                 continue
             sources[source.id] = source
     return sources
Example #14
0
    def __init__(self, context, controllerName, configPath=""):
        Controller.__init__(self, context, __file__)
        configParser = ConfigParser()
        configFilename = configPath
        if (not exists(configPath)) and exists(getenv("HOME") + "/" + controllerName + "/etc/cherrypy.conf"):
            configFilename = getenv("HOME") + "/" + controllerName + "/etc/cherrypy.conf"
        elif (
            (not exists(configPath))
            and getRoot(controllerName)
            and exists(getRoot(controllerName) + "/etc/cherrypy.conf")
        ):
            configFilename = getRoot(controllerName) + "/etc/cherrypy.conf"
        elif exists(configPath + "/etc/cherrypy.conf"):
            configFilename = configPath + "/etc/cherrypy.conf"
        elif exists(configPath):
            configFilename = configPath
        else:
            raise "File not found %s" % configFilename

        print "****************" + configFilename

        try:
            configParser.read(configFilename)
        except:
            print "Cannot read configFilename."
        self.config = configParser._sections
        print self.config
Example #15
0
    def get_interface(self, opts):
        target_ip_address = opts["ip_address"]
        bacnet_config_file = opts["bacnet_device_config"]
        config = opts.get("register_config", configFile)

        bacnet_config = ConfigParser()
        bacnet_config.read(bacnet_config_file)

        # check for BACpypes section
        if not bacnet_config.has_section("BACpypes"):
            raise RuntimeError("INI file with BACpypes section required")

        ini_obj = dict(bacnet_config.items("BACpypes"))

        self_ip_address = ini_obj["address"]

        max_apdu_len = int(ini_obj.get("max_apdu_length", 1024))

        seg_supported = ini_obj.get("segmented_supported", "segmentedBoth")
        obj_id = int(ini_obj.get("object_id", 599))
        obj_name = ini_obj.get("object_name", "sMap BACnet driver")
        ven_id = int(ini_obj.get("vendor_id", 15))

        return BACnetInterface(
            self_ip_address,
            target_ip_address,
            max_apdu_len=max_apdu_len,
            seg_supported=seg_supported,
            obj_id=obj_id,
            obj_name=obj_name,
            ven_id=ven_id,
            config_file=config,
        )
Example #16
0
def get_ws_call(action, payload, uid):
    """
    This function builds the url for the outgoing call to the different errata ws.
    :param payload: payload to be posted
    :param action: one of the 4 actions: create, update, close, retrieve
    :param uid: in case of a retrieve call, uid is needed
    :return: requests call
    """
    config = ConfigParser()
    config.read(os.path.join(os.getenv("ISSUE_CLIENT_HOME"), "esgf-client.ini"))
    if action not in ACTIONS:
        logging.error("Unrecognized command, refer to the docs for help or use -h, error code: {}.".format(6))
        sys.exit(1)

    url = config.get(WEBSERVICE, URL_BASE) + config.get(WEBSERVICE, action)
    if action in [CREATE, UPDATE]:
        r = requests.post(url, json.dumps(payload), headers=HEADERS)
    elif action == CLOSE:
        r = requests.post(url + uid)
    elif action == RETRIEVE:
        r = requests.get(url + uid)
    else:
        r = requests.get(url)
    if r.status_code != requests.codes.ok:
        logging.error(
            "Errata WS call has failed, please refer to the error text for further information: {0}"
            ", error code: {1}".format(r.text, 5)
        )
        sys.exit(1)
    return r
def init():
    options.config = os.path.abspath(options.config)
    if options.username == "all":
        options.username = None
    if options.email == "all":
        options.email = None

    config_parser = ConfigParser(
        dict(here=os.getcwd(), database_connection="sqlite:///database/universe.sqlite?isolation_level=IMMEDIATE")
    )
    config_parser.read(options.config)

    config_dict = {}
    for key, value in config_parser.items("app:main"):
        config_dict[key] = value

    config = galaxy.config.Configuration(**config_dict)
    object_store = build_object_store_from_config(config)

    from galaxy.model import mapping

    return (
        mapping.init(config.file_path, config.database_connection, create_tables=False, object_store=object_store),
        object_store,
        config.database_connection.split(":")[0],
    )
Example #18
0
    def autologin(self, section=None):
        """Login to Open Library with credentials taken from ~/.olrc file.

        The ~/.olrc file must be in ini format (format readable by
        ConfigParser module) and there should be a section with the
        server name. A sample configuration file may look like this::

            [openlibrary.org]
            username = joe
            password = secret

            [0.0.0.0:8080]
            username = joe
            password = joe123
            
        Optionally section name can be passed as argument to force using a different section name.
        """
        config = ConfigParser()
        config.read(os.path.expanduser("~/.olrc"))

        section = section or self.base_url.replace("http://", "")

        if not config.has_section(section):
            raise Exception("No section found with name %s in ~/.olrc" % repr(section))

        username = config.get(section, "username")
        password = config.get(section, "password")
        return self.login(username, password)
Example #19
0
def import_groups(options):
    log("Importing groups")
    groups_tool = options.plone.portal_groups
    groups_ini = os.path.join(options.input_directory, "groups.ini")

    CP = ConfigParser()
    CP.read([groups_ini])
    get = CP.get

    count = 0
    for section in CP.sections():
        grp_id = get(section, "name")
        members = get(section, "members").split(",")
        if options.verbose:
            log("-> %s" % grp_id)

        roles = get(section, "roles").split(",")
        groups_tool.addGroup(grp_id, roles=roles)
        grp = groups_tool.getGroupById(grp_id)
        if grp is None:
            log("   Error while creating group %s" % grp_id)
            continue
        for member in members:
            grp.addMember(member)
        count += 1

    log("%d groups imported" % count)
Example #20
0
def reload_constraints():
    """
    Parse SWIFT_CONF_FILE and reset module level global contraint attrs,
    populating OVERRIDE_CONSTRAINTS AND EFFECTIVE_CONSTRAINTS along the way.
    """
    global SWIFT_CONSTRAINTS_LOADED, OVERRIDE_CONSTRAINTS
    SWIFT_CONSTRAINTS_LOADED = False
    OVERRIDE_CONSTRAINTS = {}
    constraints_conf = ConfigParser()
    if constraints_conf.read(utils.SWIFT_CONF_FILE):
        SWIFT_CONSTRAINTS_LOADED = True
        for name in DEFAULT_CONSTRAINTS:
            try:
                value = constraints_conf.get("swift-constraints", name)
            except NoOptionError:
                pass
            except NoSectionError:
                # We are never going to find the section for another option
                break
            else:
                try:
                    value = int(value)
                except ValueError:
                    value = utils.list_from_csv(value)
                OVERRIDE_CONSTRAINTS[name] = value
    for name, default in DEFAULT_CONSTRAINTS.items():
        value = OVERRIDE_CONSTRAINTS.get(name, default)
        EFFECTIVE_CONSTRAINTS[name] = value
        # "globals" in this context is module level globals, always.
        globals()[name.upper()] = value
Example #21
0
def get_config_param(param):
    """
    Parse config file and find source dir in it
    """
    curdir = os.curdir
    if "__file__" in globals():
        curdir = os.path.dirname(os.path.abspath(__file__))

    config = None
    for loc in curdir, os.curdir, os.path.expanduser("~"):
        try:
            with open(os.path.join(loc, "precommit1c.ini")) as source:
                if sys.version_info < (3, 0, 0):
                    from ConfigParser import ConfigParser  # @NoMove @UnusedImport
                else:
                    from configparser import ConfigParser

                config = ConfigParser()
                config.read_file(source)
                break
        except IOError:
            pass

    if config is not None and config.has_option("default", param):
        value = config.get("default", param)
        return value

    return None
Example #22
0
    def restore_rois(self, roifile):
        """restore ROI setting from ROI.dat file"""
        cp = ConfigParser()
        cp.read(roifile)
        rois = []
        self.mcas[0].clear_rois()
        prefix = self.mcas[0]._prefix
        if prefix.endswith("."):
            prefix = prefix[:-1]
        iroi = 0
        for a in cp.options("rois"):
            if a.lower().startswith("roi"):
                name, dat = cp.get("rois", a).split("|")
                lims = [int(i) for i in dat.split()]
                lo, hi = lims[0], lims[1]
                roi = ROI(prefix=prefix, roi=iroi)
                roi.left = lo
                roi.right = hi
                roi.name = name.strip()
                rois.append(roi)
                iroi += 1

        epics.poll(0.050, 1.0)
        self.mcas[0].set_rois(rois)
        cal0 = self.mcas[0].get_calib()
        for mca in self.mcas[1:]:
            mca.set_rois(rois, calib=cal0)
Example #23
0
    def readConfigFile(self, config_file_name=None):
        """Reads the given config file, or if none is given, the
        default config file.

        :param config_file_name: a String specifying the name of the
           config file to read.
        """
        # Create ConfigParser and UDConfig Objects
        confparser = ConfigParser()
        self.opts = YumCronConfig()

        # If no config file name is given, fall back to the default
        if config_file_name == None:
            config_file_name = default_config_file

        # Attempt to read the config file.  confparser.read will return a
        # list of the files that were read successfully, so check that it
        # contains config_file
        if config_file_name not in confparser.read(config_file_name):
            print >> sys.stderr, "Error reading config file:", config_file_name
            sys.exit(1)

        # Populate the values into  the opts object
        self.opts.populate(confparser, "commands")
        self.opts.populate(confparser, "emitters")
        self.opts.populate(confparser, "email")
        self.opts.populate(confparser, "groups")
        self._confparser = confparser

        # If the system name is not given, set it by getting the hostname
        if self.opts.system_name == "None":
            self.opts.system_name = gethostname()

        if "None" in self.opts.group_list:
            self.opts.group_list = []
Example #24
0
def main(argv=None):
    """Main logic hit by the commandline invocation."""
    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument("config", help="path to the configuration file")
    args = parser.parse_args(argv)
    if args.config is not None:
        fileConfig(args.config)
        logger.info("Logging initialized")

    config = ConfigParser()
    config.read(args.config)
    # Grab the database uri setting from the config.
    Session = create_database_session(config.get("anomaly", "database-uri"))

    # Queue initialization
    connection = BlockingConnection()
    channel = connection.channel()
    channel.queue_declare(queue=QUEUE, durable=True, exclusive=False)

    # Setup up our consumer callback
    consumer = Consumer(Session())
    channel.basic_consume(consumer, queue=QUEUE)

    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.stop_consuming()
    connection.close()
Example #25
0
class TestAuthServiceMethods(unittest.TestCase):
    """
    Tests VolService Methods
    """

    def setUp(self):
        """
        setup
        """
        self.AuthService = AuthService.TokenService()
        self.TestCfg = ConfigParser()
        self.TestCfg.read(options.setup)
        self.Cell = self.TestCfg.get("general", "Cell").lower()
        self.User = self.TestCfg.get("general", "User")
        self.Pass = self.TestCfg.get("general", "Pass")
        return

    def test_getTokenFromShell(self):
        token = self.AuthService.getToken()
        self.assertEqual(self.Cell, token._CELL_NAME)
        return

    def test_get_artificialToken(self):
        token = self.AuthService.get_artificial_Token(123, "openafs.org")
        self.assertEqual("openafs.org", token._CELL_NAME)
        self.assertEqual(123, token._AFS_ID)
        return
Example #26
0
    def _makeInstance(self, id, portal_type, subdir, import_context):

        context = self.context
        properties = import_context.readDataFile(".properties", "%s/%s" % (subdir, id))
        tool = getToolByName(context, "portal_types")

        try:
            tool.constructContent(portal_type, context, id)
        except ValueError:  # invalid type
            return None

        content = context._getOb(id)

        if properties is not None:
            lines = properties.splitlines()

            stream = StringIO("\n".join(lines))
            parser = ConfigParser(defaults={"title": "", "description": "NONE"})
            parser.readfp(stream)

            title = parser.get("DEFAULT", "title")
            description = parser.get("DEFAULT", "description")

            content.setTitle(title)
            content.setDescription(description)

        return content
Example #27
0
 def command(self):
     try:
         config = ConfigParser({"here": self.options.here})
         config.read(self.options.config)
         return main(config, self.options.wpfile, self.options.here, self.options.wpurl, self.options.colurl)
     except:
         return traceback.format_exc()
def generateSnippet(abstDistDir, applicationIniFile, marType, downloadBaseURL, product, platform, channel, fromVersion):
    # Let's extract information from application.ini
    c = ConfigParser()
    try:
        c.readfp(open(applicationIniFile))
    except IOError, (stderror):
        sys.exit(stderror)
Example #29
0
def import_project_myos_config(project_id):
    """
    导入项目的myos配置文件
    :param project_id:
    :return:
    """

    # 保存配置文件
    new_config_file = request.files["app_config"]
    current_app.logger.info(new_config_file)
    upload_path = os.path.join(current_app.config["TMS_TEMP_DIR"], current_user.username, "ApkVersion.ini")
    if not os.path.exists(os.path.dirname(upload_path)):
        os.makedirs(os.path.dirname(upload_path))
    new_config_file.save(upload_path)

    project_apk = []
    cf = ConfigParser()
    try:
        cf.read(upload_path)
        for section in cf.sections():
            if section == "ProjectInfo":
                continue
            project_apk.append(section)

    except NoSectionError, e:
        print e
        print "[ERROR] apkVersion file config error"
Example #30
0
def isLocked(ulPath):
    nodeInfo = ConfigParser()
    nodeInfo.read(os.path.join(ulPath, ".nodeInfo"))
    if nodeInfo.get("Versioning", "locked") == "False":
        return False

    return True