def test_get_error(self): t = (None, AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual(AVConfigParserErrors.get_error(None), t) t = (999999, AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual(AVConfigParserErrors.get_error(999999), t) t = ("999999", AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual(AVConfigParserErrors.get_error("999999"), t) t = (0, AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.SUCCESS]) self.assertEqual(AVConfigParserErrors.get_error(0), t)
def read(self, filename): """Reads the given filename @param filename the ossim-setup.conf path @returns a tuple (code, "error string") """ if not os.path.isfile(filename): return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.FILE_NOT_EXIST) try: self.__sections.clear() configfile = open(filename, 'r') current_section = None nline = 0 for line in configfile.readlines(): nline += 1 if line.strip() == '' or line[0] in '#;': continue line = line.strip() sec_data = self.SECTION_REGEX.match(line) if sec_data: section_name = sec_data.group('header') if not self.__sections.has_key(section_name): current_section = section_name self.__sections[section_name] = {} else: raise DuplicatedConfigSeciton(filename=filename, lineno=nline, msg=section_name) else: opt_data = self.OPTION_REGEX.match(line) if opt_data: optname, vi, optval = opt_data.group( 'option', 'vi', 'value') if ';' in optval: # ';' is a comment delimiter only if it follows # a spacing character pos = optval.find(';') if pos != -1 and optval[pos - 1].isspace(): optval = optval[:pos] # allow empty values if optval == '""': optval = '' optname = optname.rstrip().lower() if not current_section: current_section = self.__defualt self.__sections[current_section] = {} self.__sections[current_section][optname] = optval else: raise InvalidConfigLine(filename=filename, lineno=nline, msg=line) configfile.close() except Exception, e: self.__sections.clear() return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.EXCEPTION, str(e))
def test_get_str_on_exception(self): self.assertEqual( AVConfigParserErrors.get_str_on_exception(None, None), "Exception (KeyError), Invalid error code Exception: None") self.assertEqual(AVConfigParserErrors.get_str_on_exception(0, None), "Success. Exception: None") self.assertEqual( AVConfigParserErrors.get_str_on_exception(0, KeyError), "Success. Exception: <type 'exceptions.KeyError'>") self.assertEqual( AVConfigParserErrors.get_str_on_exception(0, ValueError), "Success. Exception: <type 'exceptions.ValueError'>")
def test_get_str_on_exception(self): self.assertEqual( AVConfigParserErrors.get_str_on_exception(None, None), "Exception (KeyError), Invalid error code Exception: None", ) self.assertEqual(AVConfigParserErrors.get_str_on_exception(0, None), "Success. Exception: None") self.assertEqual( AVConfigParserErrors.get_str_on_exception(0, KeyError), "Success. Exception: <type 'exceptions.KeyError'>" ) self.assertEqual( AVConfigParserErrors.get_str_on_exception(0, ValueError), "Success. Exception: <type 'exceptions.ValueError'>", )
def test_get_error(self): t = (None, AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual(AVConfigParserErrors.get_error(None), t) t = (999999, AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual(AVConfigParserErrors.get_error(999999), t) t = ("999999", AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual(AVConfigParserErrors.get_error("999999"), t) t = (0, AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.SUCCESS]) self.assertEqual(AVConfigParserErrors.get_error(0), t)
def read(self, filename): """Reads the given filename @param filename the ossim-setup.conf path @returns a tuple (code, "error string") """ if not os.path.isfile(filename): return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.FILE_NOT_EXIST) try: self.__sections.clear() configfile = open(filename, 'r') current_section = None nline = 0 for line in configfile.readlines(): nline +=1 if line.strip() == '' or line[0] in '#;': continue line = line.strip() sec_data = self.SECTION_REGEX.match(line) if sec_data: section_name = sec_data.group('header') if not self.__sections.has_key(section_name): current_section = section_name self.__sections[section_name] = {} else: raise DuplicatedConfigSeciton(filename=filename,lineno=nline,msg=section_name) else: opt_data = self.OPTION_REGEX.match(line) if opt_data: optname, vi, optval = opt_data.group('option', 'vi', 'value') if ';' in optval: # ';' is a comment delimiter only if it follows # a spacing character pos = optval.find(';') if pos != -1 and optval[pos - 1].isspace(): optval = optval[:pos] # allow empty values if optval == '""': optval = '' optname = optname.rstrip().lower() if not current_section: current_section = self.__defualt self.__sections[current_section] = {} self.__sections[current_section][optname] = optval else: raise InvalidConfigLine(filename=filename,lineno=nline,msg=line) configfile.close() except Exception, e: self.__sections.clear() return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.EXCEPTION, str(e))
def set_hosts_config (self, entry = "2", \ ipaddr = None, canonical = None, aliases = [], \ is_new = True): """ Set the configuracion for a /etc/hosts entry. ToDo: be able to set new values. """ hosts_entry_path = "/files/etc/hosts/%s" % entry hosts_entry_list = self.__augeas.match(hosts_entry_path) if hosts_entry_list == []: return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.HOSTS_ENTRY_NOT_FOUND, additional_message=str(entry)) if ipaddr != None: self.__augeas.set(hosts_entry_path + '/ipaddr', ipaddr) self.__pending['host %s address' % entry] = ipaddr if canonical != None: self.__augeas.set(hosts_entry_path + '/canonical', canonical) self.__pending['host %s canonical name' % entry] = canonical if aliases != []: for counter, alias in enumerate(aliases, start=1): self.__augeas.set(hosts_entry_path + '/alias[%d]' % counter, alias) self.__pending['host %s alias[%d]' % (entry, counter)] = alias return AVConfigParserErrors.ALL_OK
def write(self, filename): """Write an .ini-format representation of the configuration state. Returns true on success, false otherwise """ try: fp = open(filename, 'w') if self.__sections.has_key(self.__defualt): sorted_keys = sorted(self.__sections[self.__defualt].keys()) for key in sorted_keys: value = self.__sections[self.__defualt][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in sorted(self.__sections.keys()): if section == self.__defualt: continue fp.write("[%s]\n" % section) sorted_keys = sorted(self.__sections[section].keys()) for key in sorted_keys: value = self.__sections[section][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") except Exception, e: return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.EXCEPTION, str(e))
def set_hosts_config (self, entry = "2", \ ipaddr = None, canonical = None, aliases = [], \ is_new = True): """ Set the configuracion for a /etc/hosts entry. ToDo: be able to set new values. """ hosts_entry_path = "/files/etc/hosts/%s" % entry hosts_entry_list = self.__augeas.match(hosts_entry_path) if hosts_entry_list == []: return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.HOSTS_ENTRY_NOT_FOUND, additional_message=str(entry)) if ipaddr != None: self.__augeas.set(hosts_entry_path + '/ipaddr', ipaddr) self.__pending['host %s address' % entry] = ipaddr if canonical != None: self.__augeas.set(hosts_entry_path + '/canonical', canonical) self.__pending['host %s canonical name' % entry] = canonical if aliases != []: for counter, alias in enumerate(aliases, start = 1): self.__augeas.set(hosts_entry_path + '/alias[%d]' % counter, alias) self.__pending['host %s alias[%d]' % (entry, counter)] = alias return AVConfigParserErrors.ALL_OK
def test_get_error_msg(self): t = (None, AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE] + "<TTT>") self.assertEqual(AVConfigParserErrors.get_error_msg(None, "TTT"), t) t = (999999, AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE] + "<TTT>") self.assertEqual(AVConfigParserErrors.get_error_msg(999999, "TTT"), t) t = ("999999", AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE] + "<TTT>") self.assertEqual(AVConfigParserErrors.get_error_msg("999999", "TTT"), t) t = (0, AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.SUCCESS] + "<TTT>") self.assertEqual(AVConfigParserErrors.get_error_msg(0, "TTT"), t)
def test_get_str(self): # Test invalid code: self.assertEqual( AVConfigParserErrors.get_str("unknowcode"), AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE], ) self.assertEqual( AVConfigParserErrors.get_str(None), AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE], ) self.assertEqual( AVConfigParserErrors.get_str(1000), AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.FILE_NOT_EXIST], ) self.assertEqual( AVConfigParserErrors.get_str(0), AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.SUCCESS] )
def test_get_str(self): #Test invalid code: self.assertEqual( AVConfigParserErrors.get_str("unknowcode"), AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual( AVConfigParserErrors.get_str(None), AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE]) self.assertEqual( AVConfigParserErrors.get_str(1000), AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.FILE_NOT_EXIST]) self.assertEqual( AVConfigParserErrors.get_str(0), AVConfigParserErrors.ERROR_CODE_MAP_STR[ AVConfigParserErrors.SUCCESS])
def test_get_error_msg(self): t = (None, AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE] + "<TTT>") self.assertEqual(AVConfigParserErrors.get_error_msg(None, "TTT"), t) t = ( 999999, AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE] + "<TTT>", ) self.assertEqual(AVConfigParserErrors.get_error_msg(999999, "TTT"), t) t = ( "999999", AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.EXCEPTION_INVALID_ERROR_CODE] + "<TTT>", ) self.assertEqual(AVConfigParserErrors.get_error_msg("999999", "TTT"), t) t = (0, AVConfigParserErrors.ERROR_CODE_MAP_STR[AVConfigParserErrors.SUCCESS] + "<TTT>") self.assertEqual(AVConfigParserErrors.get_error_msg(0, "TTT"), t)
def apply_changes (self): """ Apply pending changes and reload configuration. """ if not self.is_pending(): return AVConfigParserErrors.ALL_OK try: self.__augeas.save() except IOError, msg: return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.CANNOT_SAVE_SYSCONFIG, str(msg))
def apply_changes(self): """ Apply pending changes and reload configuration. """ if not self.is_pending(): return AVConfigParserErrors.ALL_OK try: self.__augeas.save() except IOError, msg: return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.CANNOT_SAVE_SYSCONFIG, str(msg))
def set_net_iface_config (self, iface, address = None, netmask = None, gateway = None, \ dns_search= None, dns_nameservers = None, \ broadcast = None, network = None, \ is_new = True): """ Set the network configuration for the interface 'iface'. """ iface_path_list = self.__augeas.match( "/files/etc/network/interfaces/iface[. = '%s']" % iface) if iface_path_list == []: if is_new: self.__augeas.set( "/files/etc/network/interfaces/iface[last() + 1]", iface) self.__augeas.set( "/files/etc/network/interfaces/auto[last() + 1]/1", iface) iface_path = "/files/etc/network/interfaces/iface[last()]" self.__augeas.set(iface_path + '/family', 'inet') self.__augeas.set(iface_path + '/method', 'static') self.__pending['%s family' % iface] = 'inet' self.__pending['%s method' % iface] = 'static' else: return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.NETWORK_INTERFACE_DOWN, additional_message=str(iface)) else: iface_path = iface_path_list[0] if address != None: self.__augeas.set(iface_path + '/address', address) self.__pending['%s address' % iface] = address if netmask != None: self.__augeas.set(iface_path + '/netmask', netmask) self.__pending['%s netmask' % iface] = netmask if gateway != None: self.__augeas.set(iface_path + '/gateway', gateway) self.__pending['%s gateway' % iface] = gateway if dns_search != None: self__augeas.set(iface_path + '/dns-search', dns_search) self.__pending['%s domain' % iface] = dns_search if dns_nameservers != None: self.__augeas.set(iface_path + '/dns-nameservers', dns_nameservers) self.__pending['%s nameserver(s)' % iface] = dns_nameservers if broadcast != None: self.__augeas.set(iface_path + '/broadcast', broadcast) self.__pending['%s broadcast' % iface] = broadcast if network != None: self.__augeas.set(iface_path + '/network', network) self.__pending['%s network' % iface] = network return AVConfigParserErrors.ALL_OK
def set_net_iface_config (self, iface, address = None, netmask = None, gateway = None, \ dns_search= None, dns_nameservers = None, \ broadcast = None, network = None, \ is_new = True): """ Set the network configuration for the interface 'iface'. """ iface_path_list = self.__augeas.match("/files/etc/network/interfaces/iface[. = '%s']" % iface) if iface_path_list == []: if is_new: self.__augeas.set("/files/etc/network/interfaces/iface[last() + 1]", iface) self.__augeas.set("/files/etc/network/interfaces/auto[last() + 1]/1", iface) iface_path = "/files/etc/network/interfaces/iface[last()]" self.__augeas.set(iface_path + '/family', 'inet') self.__augeas.set(iface_path + '/method', 'static') self.__pending['%s family' % iface] = 'inet' self.__pending['%s method' % iface] = 'static' else: return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.NETWORK_INTERFACE_DOWN, additional_message=str(iface)) else: iface_path = iface_path_list[0] if address != None: self.__augeas.set(iface_path + '/address', address) self.__pending['%s address' % iface] = address if netmask != None: self.__augeas.set(iface_path + '/netmask', netmask) self.__pending['%s netmask' % iface] = netmask if gateway != None: self.__augeas.set(iface_path + '/gateway', gateway) self.__pending['%s gateway' % iface] = gateway if dns_search != None: self__augeas.set(iface_path + '/dns-search', dns_search) self.__pending['%s domain' % iface] = dns_search if dns_nameservers != None: self.__augeas.set(iface_path + '/dns-nameservers', dns_nameservers) self.__pending['%s nameserver(s)' % iface] = dns_nameservers if broadcast != None: self.__augeas.set(iface_path + '/broadcast', broadcast) self.__pending['%s broadcast' % iface] = broadcast if network != None: self.__augeas.set(iface_path + '/network', network) self.__pending['%s network' % iface] = network return AVConfigParserErrors.ALL_OK
def write(self, filename): """Write an .ini-format representation of the configuration state. Returns true on success, false otherwise """ try: fp = open(filename, 'w') if self.__sections.has_key(self.__defualt): sorted_keys = sorted(self.__sections[self.__defualt].keys()) for key in sorted_keys: value = self.__sections[self.__defualt][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in sorted(self.__sections.keys()): if section == self.__defualt: continue fp.write("[%s]\n" % section) sorted_keys = sorted(self.__sections[section].keys()) for key in sorted_keys: value = self.__sections[section][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") except Exception, e: return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.EXCEPTION, str(e))
fp = open(filename, 'w') if self.__sections.has_key(self.__defualt): sorted_keys = sorted(self.__sections[self.__defualt].keys()) for key in sorted_keys: value = self.__sections[self.__defualt][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in sorted(self.__sections.keys()): if section == self.__defualt: continue fp.write("[%s]\n" % section) sorted_keys = sorted(self.__sections[section].keys()) for key in sorted_keys: value = self.__sections[section][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") except Exception, e: return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.EXCEPTION, str(e)) return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.SUCCESS) def set(self, section, option, value): """Set an option.""" result = True if not section or section == "": section = self.__defualt try: self.__sections[section][option] = value except KeyError: result = False return result
class AVConfigParser(): """Class to read INI files Note: we can't use ConfigParser due to the ossim_setup.conf file format. It's possible to find values without section. This code is based on python2.6 RawConfigParser """ VARIABLES_WITHOUT_SECTION = "DEFAULT" SECTION_REGEX = re.compile("\[(?P<header>[^]]+)\]") OPTION_REGEX = re.compile( "^(?P<option>[^\[\]:=\s][^\[\]:=]*)\s*(?P<vi>[:=])\s*(?P<value>.*)$") BOOLEAN_VALUES = { '1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False } def __init__(self, default_section_for_values_without_section=None): """Constructor @param default_section_for_values_without_section: Name of the section assigned to those variables that doesn't have section. """ self.__filename = "" self.__sections = {} self.__defualt = self.VARIABLES_WITHOUT_SECTION if default_section_for_values_without_section: self.__defualt = default_section_for_values_without_section def sections(self): """Returns the list of section names. Those values without section will be in the default section """ return self.__sections.keys() def has_section(self, section): """Indicate whether the named section is present in the configuration.""" return self.__sections.has_key(section) def options(self, section): """Return the list of option names for the given section name""" if self.__sections.has_key(section): return self.__sections[section].keys() return [] def read(self, filename): """Reads the given filename @param filename the ossim-setup.conf path @returns a tuple (code, "error string") """ if not os.path.isfile(filename): return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.FILE_NOT_EXIST) try: self.__sections.clear() configfile = open(filename, 'r') current_section = None nline = 0 for line in configfile.readlines(): nline += 1 if line.strip() == '' or line[0] in '#;': continue line = line.strip() sec_data = self.SECTION_REGEX.match(line) if sec_data: section_name = sec_data.group('header') if not self.__sections.has_key(section_name): current_section = section_name self.__sections[section_name] = {} else: raise DuplicatedConfigSeciton(filename=filename, lineno=nline, msg=section_name) else: opt_data = self.OPTION_REGEX.match(line) if opt_data: optname, vi, optval = opt_data.group( 'option', 'vi', 'value') if ';' in optval: # ';' is a comment delimiter only if it follows # a spacing character pos = optval.find(';') if pos != -1 and optval[pos - 1].isspace(): optval = optval[:pos] # allow empty values if optval == '""': optval = '' optname = optname.rstrip().lower() if not current_section: current_section = self.__defualt self.__sections[current_section] = {} self.__sections[current_section][optname] = optval else: raise InvalidConfigLine(filename=filename, lineno=nline, msg=line) configfile.close() except Exception, e: self.__sections.clear() return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.EXCEPTION, str(e)) return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.SUCCESS)
for key in sorted_keys: value = self.__sections[self.__defualt][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in sorted(self.__sections.keys()): if section == self.__defualt: continue fp.write("[%s]\n" % section) sorted_keys = sorted(self.__sections[section].keys()) for key in sorted_keys: value = self.__sections[section][key] fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") except Exception, e: return AVConfigParserErrors.get_error_msg( AVConfigParserErrors.EXCEPTION, str(e)) return AVConfigParserErrors.get_error_msg(AVConfigParserErrors.SUCCESS) def set(self, section, option, value): """Set an option.""" result = True if not section or section == "": section = self.__defualt try: self.__sections[section][option] = value except KeyError: result = False return result