当前位置: 首页>>代码示例>>Python>>正文


Python DictOp.get方法代码示例

本文整理汇总了Python中karesansui.lib.dict_op.DictOp.get方法的典型用法代码示例。如果您正苦于以下问题:Python DictOp.get方法的具体用法?Python DictOp.get怎么用?Python DictOp.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在karesansui.lib.dict_op.DictOp的用法示例。


在下文中一共展示了DictOp.get方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
class xmlLikeConfParser:

    _delim               = "[ \t]+"
    _new_delim           = " "
    _comment             = "#"
    _reserved_key_prefix = "@"
    _indent              = "  "

    _module  = "xml_like_conf_parser"
    _footer  = "-- Generated by karesansui"

    def __init__(self,paths=[]):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})
        self.set_source_file(paths)

        self.opt_uni   = ['PIDFile']
        self.opt_multi = ['LoadPlugin','Include']
        self.opt_sect  = ['Directory','VirtualHost','View']

    def set_opt_uni(self, opts):
        self.opt_uni = opts

    def set_opt_multi(self, opts):
        self.opt_multi = opts

    def set_opt_sect(self, opts):
        self.opt_sect = opts

    def set_delim(self, delim=" "):
        self._delim = delim

    def set_new_delim(self, delim=" "):
        self._new_delim = delim

    def set_comment(self, comment="#"):
        self._comment = comment

    def set_reserved_key_prefix(self, prefix="@"):
        self._reserved_key_prefix = prefix

    def set_footer(self, footer=""):
        self._footer = footer

    def set_source_file(self,paths=[]):
        if type(paths) == str:
            paths = [paths]
        self.paths = paths
        return True

    def get_source_file(self):
        return self.paths

    def source_file(self):
        return self.get_source_file()

    def build_value(self, value=None, precomment=[], postcomment=None):
        if type(precomment) == str:
            precomment = [precomment]
        return [value, [precomment, postcomment], ]

    def read_conf(self):
        retval = {}
        orders_key = "%sORDERS" % (self._reserved_key_prefix,)

        for _afile in self.source_file():
            res = ConfigFile(_afile).read()
            self.orders = []
            self.dop.set(self._module,[_afile],self._read_conf(res))
            self.dop.set(self._module,[_afile,orders_key],self.orders)

        return self.dop.getconf(self._module)

    def _read_conf(self,lines,level=0):

        dop = DictOp()
        dop.addconf("__",{})

        pre_comment  = []   # 設定の前のコメント リスト配列
        post_comment = None # 設定行のコメント 文字列
        _in_section = False
        _res = []
        for _aline in lines:

            if _in_section is True:
                regex = "[ \t]*(?P<comment>#*)[ \t]*</(?P<key>%s)>" % _section_key #'|'.join(self.opt_sect)
                _regex = re.compile(r"%s" % regex)
                m = _regex.match(_aline)
                if m:
                    _comment = m.group('comment')
                    _key     = m.group('key').strip()
                    values = self.build_value(self._read_conf(_res,level),pre_comment,post_comment)
                    dop.set("__",[_key,_section_val],values)
                    if _comment != "":
                        dop.comment("__",[_key,_section_val])
                    if level == 1:
                        self.orders.append([_key,_section_val])
                    pre_comment  = []
                    post_comment = None
                    _in_section = False
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:xml_like_conf_parser.py

示例2: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
class shConfParser:

    _delim               = "="
    _new_delim           = "="
    _comment             = "#"
    _multidefine         = False
    _reserved_key_prefix = "@"

    _module      = "sh_conf_parser"

    def __init__(self,paths=[]):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})
        self.set_source_file(paths)

    def set_delim(self, delim="="):
        self._delim = delim

    def set_new_delim(self, delim="="):
        self._new_delim = delim

    def set_comment(self, comment="#"):
        self._comment = comment

    def set_multidefine(self, multidefine=False):
        self._multidefine = multidefine

    def set_reserved_key_prefix(self, prefix="@"):
        self._reserved_key_prefix = prefix

    def set_source_file(self,paths=[]):
        if type(paths) == str:
            paths = [paths]
        self.paths = paths
        return True

    def get_source_file(self):
        return self.paths

    def source_file(self):
        return self.get_source_file()

    def read_conf(self):
        retval = {}

        for _afile in self.source_file():
            res = ConfigFile(_afile).read()

            orders    = []
            for _aline in res:
                _aline = _aline.rstrip('\r\n')

                regex_str = "^(?P<comment>%s)?[ \t]*(?P<key>[^%s ]+)[ \t]*%s *(?P<value>.*)$" % (self._comment,self._delim,self._delim,)
                regex = re.compile(r"%s" % regex_str)

                m = regex.match(_aline)
                if m:
                    comment = m.group('comment')
                    key     = m.group('key')
                    value   = m.group('value')
                    if not value.rfind(self._comment) == -1:
                        value = value[:value.rfind(self._comment)]

                    if self._multidefine and self.dop.isset(self._module,[_afile,key]) is True:
                        new_value = self.dop.get(self._module,[_afile,key])
                        if type(new_value) == str:
                            new_value = [new_value]
                        if not value in new_value:
                            new_value.append(value)
                    else:
                        new_value = value
                    self.dop.set(self._module,[_afile,key],new_value)
                    if not key in orders:
                        orders.append(key)

                    if comment is not None:
                        self.dop.comment(self._module,[_afile,key])

            orders_key = "%sORDERS" % (self._reserved_key_prefix,)
            self.dop.set(self._module,[_afile,orders_key],orders)

        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)


    def _value_to_lines(self,value):
        lines = []

        for _k,_v in value.iteritems():

            try:
                if _v['action'] == "delete":
                    continue
            except:
                pass

            try:
                val = _v['value']

                comment = False
#.........这里部分代码省略.........
开发者ID:goura,项目名称:karesansui,代码行数:103,代码来源:sh_conf_parser.py

示例3: process

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        exist_bond_list = get_ifconfig_info("regex:^bond")
        if opts.dev not in exist_bond_list:
            raise KssCommandOptException('Target bonding device not found. target=%s' % opts.dev)

        self.up_progress(10)
        dop = DictOp()
        ifcfg_parser = ifcfgParser()
        dop.addconf("ifcfg", ifcfg_parser.read_conf())
        if dop.getconf("ifcfg") == {}:
            raise KssCommandException('Failure read network config file.')

        if dop.get("ifcfg", opts.dev) is False:
            raise KssCommandException('Target device ifcfg file not found.')

        self.up_progress(10)
        restore_dev_list = []
        for dev in dop.getconf("ifcfg").keys():
            if dop.get("ifcfg", [dev, "MASTER"]) == opts.dev:
                restore_dev_list.append(dev)

        self.up_progress(10)
        if opts.succession is True:
            bond_bridge = dop.get("ifcfg", [opts.dev, "BRIDGE"])
            bond_dev = opts.dev
            if bond_bridge:
                bond_dev = bond_bridge

            ipaddr = dop.get("ifcfg",  [bond_dev, "IPADDR"])
            netmask = dop.get("ifcfg", [bond_dev, "NETMASK"])
            gateway = dop.get("ifcfg", [bond_dev, "GATEWAY"])
            bonding_opts = dop.get("ifcfg", [opts.dev, "BONDING_OPTS"])
            bonding_opts = bonding_opts.strip('"')
            primary_dev = None
            for combination in bonding_opts.split(" "):
                if re.match("primary", combination):
                    (key,val) = combination.split("=")
                    val = val.strip()
                    primary_dev = val

        self.up_progress(10)
        for restore_dev in restore_dev_list:
            if move_file("%s/ifcfg-%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev), NETWORK_IFCFG_DIR) is False:
                raise KssCommandException('Failure restore ifcfg file.')
            if os.path.isfile("%s/ifcfg-p%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev)):
                if move_file("%s/ifcfg-p%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev), NETWORK_IFCFG_DIR) is False:
                    raise KssCommandException('Failure restore ifcfg file.')

        self.up_progress(10)
        if opts.succession is True and primary_dev is not None:
            dop = DictOp()
            ifcfg_parser = ifcfgParser()
            dop.addconf("ifcfg", ifcfg_parser.read_conf())
            if dop.getconf("ifcfg") == {}:
                raise KssCommandException('Failure read network config file.')

            if ipaddr:
                dop.set("ifcfg", [primary_dev, "IPADDR"],  ipaddr)
            if netmask:
                dop.set("ifcfg", [primary_dev, "NETMASK"], netmask)
            if gateway:
                dop.set("ifcfg", [primary_dev, "GATEWAY"], gateway)

            if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False:
                raise KssCommandException('Failure write network config file.')

        self.up_progress(10)
        remove_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, opts.dev))

        self.up_progress(10)
        dop = DictOp()
        modprobe_parser = modprobe_confParser()
        dop.addconf("modprobe_conf", modprobe_parser.read_conf())
        if dop.getconf("modprobe_conf") == {}:
            raise KssCommandException('Failure read modprobe config file.')

        dop.unset("modprobe_conf", ["alias", opts.dev])

        if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False:
            raise KssCommandException('Failure write modprobe config file.')

        self.up_progress(10)

        #
        # Delete bridge device
        #
        bridge_list = get_bridge_info()
        bond_bridge = None

        for bridge in bridge_list:
            if opts.dev in bridge_list[bridge]:
                bond_bridge = bridge

        if bond_bridge:
            ifdown_cmd = (NETWORK_IFDOWN_COMMAND,
                          bond_bridge,
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:delete_bonding.py

示例4: _value_to_lines

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
    def _value_to_lines(self,conf_arr,level=0):
        lines = []
        orders_key = "%sORDERS" % (self._reserved_key_prefix,)

        dop = DictOp()
        dop.addconf("__",conf_arr)

        for _k,_v in dop.getconf("__").iteritems():

            action = dop.action("__",[_k])
            if action == "delete":
                continue

            iscomment = dop.iscomment("__",[_k])

            value = dop.get("__",[_k])

            if type(value) == list:

                _val          = value[0]

                if type(_val) != dict:
                    _pre_comment  = value[1][0]
                    _post_comment = value[1][1]

                    pre_comment = []
                    try:
                        for _aline in _pre_comment:
                            if _aline.strip() == "":
                                pass
                            elif _aline[0:1] != self._comment:
                                _prefix = ""
                                if level > 0:
                                    _prefix += str_repeat(self._indent,level)
                                _prefix += self._comment
                                _aline = "%s %s" % (_prefix,_aline,)
                            pre_comment.append(_aline)
                    except:
                        pass

                    if len(pre_comment) > 0:
                        #preprint_r(pre_comment)
                        lines = lines + pre_comment

                    post_comment = _post_comment
                    try:
                        if post_comment is not None and post_comment[0:1] != self._comment:
                            post_comment = "%s %s" % (self._comment,post_comment,)
                    except:
                        pass
                else:
                    pass

            else:
                _val = value

            _prefix = ""
            if iscomment is True:
                _prefix += self._comment
            if level > 0:
                _prefix += str_repeat(self._indent,level)

            if type(_val) == dict:

                # ORDER順に設定する
                orders = []
                try:
                    old_orders = _val[orders_key]['value']
                except:
                    old_orders = []

                for kk in old_orders:
                    if type(kk) is list:
                        orders.append(kk[0])
                    elif type(kk) is str:
                        orders.append(kk)

                for kk in _val.keys():
                    if not kk in orders:
                        orders.append(kk)

                #for _k2,_v2 in _val.iteritems():
                for _k2 in orders:

                    if _k2 == orders_key:
                        continue
                    _v2 = _val[_k2]

                    sub_value = {}
                    sub_value[_k2] = _v2

                    try:
                        iscomment = sub_value[_k2]['comment']
                    except:
                        iscomment = False

                    try:
                        action = sub_value[_k2]['action']
                    except:
                        action = ""
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:xml_like_conf_parser.py

示例5: preprint_r

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
    # 'LoadPlugin target_replace' の値を取得
    key = ["LoadPlugin","target_hoge"]
    dop.insert_order("dum",key)
    value = dop.cdp_get("dum",key)
    preprint_r(value)

    # 'LoadPlugin target_replace' の設定順を取得
    key = ["LoadPlugin","target_hoge"]
    num = dop.order("dum",key)
    print num

    # '<Plugin foobar>' を 'LoadPlugin target_hoge' の前にする
    key = ["Plugin","foobar"]
    dop.insert_order("dum",key,num)

    # '<Plugin foobar>' を 'LoadPlugin target_hoge' の後に変更する
    dop.change_order("dum",key,num+1)

    # 'Foo' を 'Bar' の後に変更する
    num = dop.order("dum",['Foo'])
    dop.change_order("dum",['Bar'],num+1)
    print dop.get("dum",['@ORDERS'])

    # 配列確認
    conf = dop.getconf("dum")
    #preprint_r(conf)

    #parser.set_footer("")
    parser.write_conf(conf,dryrun=True)

开发者ID:AdUser,项目名称:karesansui,代码行数:31,代码来源:collectd.py

示例6: process

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        dev_list = comma_split(opts.dev)
        if len(dev_list) < 2:
            # TRANSLATORS:
            #    bondingするためのdeviceが少ないです
            raise KssCommandOptException('ERROR: Small device for bonding. - dev=%s' % (opts.dev))

        interface_list = get_ifconfig_info()
        for dev in dev_list:
            if dev not in interface_list:
                raise KssCommandOptException('ERROR: Bonding target device not found. - dev=%s' % (dev))

        if opts.primary not in dev_list:
            raise KssCommandOptException('ERROR: Primary device not found in bonding device. - primary=%s dev=%s' % (opts.primary, opts.dev))

        exist_bond_max_num = -1
        exist_bond_list = get_ifconfig_info("regex:^bond")
        for bond_name in exist_bond_list.keys():
            try:
                num = int(bond_name.replace("bond",""))
            except ValueError:
                continue

            if exist_bond_max_num < num:
                exist_bond_max_num = num

        self.up_progress(10)
        physical_bond_name = "bond%s" % (exist_bond_max_num + 1)
        bridge_bond_name = "bondbr%s" % (exist_bond_max_num + 1)
        bond_options = '"mode=%s primary=%s miimon=%s"' % (opts.mode, opts.primary, BONDING_CONFIG_MII_DEFAULT)
        self.up_progress(10)

        dop = DictOp()
        ifcfg_parser = ifcfgParser()
        modprobe_parser = modprobe_confParser()

        dop.addconf("ifcfg", ifcfg_parser.read_conf())
        if dop.getconf("ifcfg") == {}:
            raise KssCommandException('Failure read network config file.')

        dop.addconf("modprobe_conf", modprobe_parser.read_conf())
        if dop.getconf("modprobe_conf") == {}:
            raise KssCommandException('Failure read modprobe config file.')

        self.up_progress(10)
        eth_conf_copykey = ["HWADDR",
                            "BOOTPROTO",
                            "ONBOOT",
                            "USERCTL",
                            ]
        bond_conf_nocopykey = ["TYPE",
                               "HWADDR",
                               "MACADDR",
                               "ETHTOOL_OPTS",
                               "ESSID",
                               "CHANNEL",
                               ]

        self.up_progress(10)
        for dev in dev_list:
            conf = dop.get("ifcfg", dev)
            if dev == opts.primary:
                primary_conf = copy.deepcopy(conf)

            dop.unset("ifcfg", dev)
            dop.set("ifcfg", [dev, "DEVICE"], conf["DEVICE"]["value"])
            for key in eth_conf_copykey:
                if key in conf:
                    dop.set("ifcfg", [dev, key], conf[key]["value"])
            dop.set("ifcfg", [dev, "MASTER"], physical_bond_name)
            dop.set("ifcfg", [dev, "SLAVE"], "yes")
            dop.set("ifcfg", [dev, "BOOTPROTO"], "none")

            if dop.get("ifcfg", "p%s" % (dev)):
                hwaddr = dop.get("ifcfg", ["p%s" % (dev), "HWADDR"])
                if hwaddr:
                    dop.set("ifcfg", [dev, "HWADDR"], hwaddr)
                dop.unset("ifcfg", "p%s" % (dev))

        for key in bond_conf_nocopykey:
            if key in primary_conf:
                del primary_conf[key]

        dop.set("ifcfg", bridge_bond_name, primary_conf)
        dop.set("ifcfg", [bridge_bond_name, "DEVICE"], bridge_bond_name)
        dop.set("ifcfg", [bridge_bond_name, "TYPE"], "Bridge")

        dop.set("ifcfg", [physical_bond_name, "DEVICE"], physical_bond_name)
        dop.set("ifcfg", [physical_bond_name, "BRIDGE"], bridge_bond_name)
        dop.set("ifcfg", [physical_bond_name, "BOOTPROTO"], "none")
        dop.set("ifcfg", [physical_bond_name, "ONBOOT"], dop.get("ifcfg", [bridge_bond_name, "ONBOOT"]))
        dop.set("ifcfg", [physical_bond_name, "BONDING_OPTS"], bond_options)

        self.up_progress(10)
        dop.set("modprobe_conf", ["alias", physical_bond_name], "bonding")

#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:add_bonding.py

示例7:

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
    # 下記 を追加
    # <Plugin "foobar">
    #        <View "hoge">
    #                SubOpt1         gege # post
    #        </View>
    #        Option2         false
    #        Option1         true
    # </Plugin>
    dop.cdp_set("dum",[new_plugin_name,"Plugin","foobar","Option1"],"true",multiple_file=True)
    dop.cdp_set("dum",[new_plugin_name,"Plugin","foobar","Option2"],"false",multiple_file=True)
    dop.cdp_set_pre_comment("dum",[new_plugin_name,"Plugin","foobar","Option2"],"pre comment",multiple_file=True)
    dop.cdp_set_post_comment("dum",[new_plugin_name,"Plugin","foobar","Option2"],"post comment",multiple_file=True)
    dop.cdp_set("dum",[new_plugin_name,"Plugin","foobar","View","hoge","SubOpt1"],"gege",multiple_file=True)
    dop.cdp_set_post_comment("dum",[new_plugin_name,"Plugin","foobar","View","hoge","SubOpt1"],"post",multiple_file=True)

    print dop.get("dum",["filter","@ORDERS"],multiple_file=True)

    # 複数ファイルを読み込むパーサーの場合は、is_parent_parser=Trueにすること
    # '<Plugin foobar>' を 先頭にする
    key = [new_plugin_name,"Plugin","foobar"]
    dop.insert_order("dum",key,0,is_parent_parser=True)

    # 'LoadPlugin target_hoge' を 先頭にする => '<Plugin foobar>' は2番目になる
    key = [new_plugin_name,"LoadPlugin","target_hoge"]
    dop.insert_order("dum",key,0,is_parent_parser=True)

    # 'Foo foo' を 先頭にする => 'LoadPlugin target_hoge' は2番目になる
    key = [new_plugin_name,"Foo"]
    dop.insert_order("dum",key,0,is_parent_parser=True)

    # work completely
开发者ID:AdUser,项目名称:karesansui,代码行数:33,代码来源:collectdplugin.py

示例8: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
class commentDealParser:

    _delim               = "[ \t]+"
    _new_delim           = " "
    _comment             = "#"
    _reserved_key_prefix = "@"

    _module  = "comment_deal_parser"
    _footer  = "-- Generated by karesansui"

    def __init__(self,paths=[]):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})
        self.set_source_file(paths)

    def set_delim(self, delim=" "):
        self._delim = delim

    def set_new_delim(self, delim=" "):
        self._new_delim = delim

    def set_comment(self, comment="#"):
        self._comment = comment

    def set_reserved_key_prefix(self, prefix="@"):
        self._reserved_key_prefix = prefix

    def set_footer(self, footer=""):
        self._footer = footer

    def set_source_file(self,paths=[]):
        if type(paths) == str:
            paths = [paths]
        self.paths = paths
        return True

    def get_source_file(self):
        return self.paths

    def source_file(self):
        return self.get_source_file()

    def build_value(self, string, precomment=[], postcomment=None):
        if type(precomment) == str:
            precomment = [precomment]
        return [string, [precomment, postcomment], ]

    def read_conf(self):
        retval = {}

        for _afile in self.source_file():
            res = ConfigFile(_afile).read()

            orders    = []
            comment_1 = []   # 設定の前のコメント リスト配列
            comment_2 = None # 設定行のコメント 文字列
            for _aline in res:
                _aline = _aline.rstrip('\r\n')

                if _aline.strip() == "":
                    comment_1.append(_aline)
                    continue

                if _aline.lstrip()[0:1] == self._comment:
                    footer_regex = re.compile(self._footer)
                    m = footer_regex.search(_aline)
                    if not m:
                        comment = _aline[_aline.rfind(self._comment):]
                        comment_1.append(comment)
                        continue

                regex_str = "^(?P<key>[^ \t]+)%s(?P<value>.*)$" % (self._delim,)
                regex = re.compile(r"%s" % regex_str)

                m = regex.match(_aline)
                if m:
                    key     = m.group('key')
                    value   = m.group('value')
                    if not value.rfind(self._comment) == -1:
                        comment_2 = value[value.rfind(self._comment):]
                        value = value[:value.rfind(self._comment)]

                    new_value = self.build_value(value,comment_1,comment_2)
                    if new_value is not False:
                        self.dop.set(self._module,[_afile,key],new_value)
                        orders.append(key)
                    comment_1 = []
                    comment_2 = None

            if len(comment_1) > 0:
                eof_key    = "%sEOF"    % (self._reserved_key_prefix,)
                new_value = self.build_value("",comment_1,comment_2)
                self.dop.set(self._module,[_afile,eof_key],new_value)

            orders_key = "%sORDERS" % (self._reserved_key_prefix,)
            self.dop.set(self._module,[_afile,orders_key],orders)

        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

#.........这里部分代码省略.........
开发者ID:goura,项目名称:karesansui,代码行数:103,代码来源:comment_deal_parser.py

示例9: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
class iptablesParser:

    _module = "iptables"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.base_parser_name = self.parser.__class__.__name__
        pass

    def source_file(self):
        retval = [PARSER_IPTABLES_CONF]

        return retval

    def read_conf(self,extra_args=None):
        retval = {}

        self.parser.set_source_file([PARSER_IPTABLES_CONF])
        self.dop.addconf(self._module,{})

        conf_arr = self.parser.read_conf()
        try:
            lines = conf_arr[PARSER_IPTABLES_CONF]['value']
            lint = self.do_lint("\n".join(lines))
            self.dop.set(self._module,["config"],lines)
            self.dop.set(self._module,["lint"]  ,lint)
        except:
            pass

        cmdfile = "cmd:%s" % PARSER_COMMAND_IPTABLES_SAVE
        self.parser.set_source_file([cmdfile])
        conf_arr = self.parser.read_conf()
        try:
            lines = conf_arr[cmdfile]['value']
            self.dop.set(self._module,["status"],lines)
        except:
            pass

        self.parser.set_source_file([PARSER_IPTABLES_CONF])

        self.dop.set(self._module,['@BASE_PARSER'],self.base_parser_name)
        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

    def write_conf(self,conf_arr={},extra_args=None,dryrun=False):
        retval = True

        now = time.strftime("%c",time.localtime())
        try:
            self.dop.addconf("parser",{})

            lines = conf_arr["config"]["value"]
            lines = array_replace(lines,PARSER_IPTABLES_CONF_HEADER,"# Generated by karesansui on %s" % (now,))
            lines = array_replace(lines,PARSER_IPTABLES_CONF_FOOTER,"# Completed on %s" % (now,))
            self.dop.set("parser",[PARSER_IPTABLES_CONF],lines)
            #self.dop.preprint_r("parser")
            arr = self.dop.getconf("parser")
            self.parser.write_conf(arr,dryrun=dryrun)
            self.do_condrestart()
        except:
            pass

        return retval

    def do_start(self):
        return self._do("start")

    def do_stop(self):
        return self._do("stop")

    def do_restart(self):
        return self._do("restart")

    def do_condrestart(self):
        return self._do("condrestart")

    def do_status(self):
        return self._do("status")

    def is_running(self):
        return self.do_status()[0]

    def _do(self,action=None):
        from karesansui.lib.utils import execute_command

        retval = False
        res    = []
        if re.match("^(%s)$" % PARSER_IPTABLES_INITRD_ACTIONS, action):
            command_args = [PARSER_IPTABLES_INITRD,action]
            (ret,res) = execute_command(command_args)
            if ret == 0:
                retval = True
        return [retval,res]

    # reverseがFalseなら設定ファイルをもとに、システムに反映(condrestart)
    # reverseがTrueならシステムの状態をもとに、設定ファイルに反映
    def do_sync(self,reverse=False):
#.........这里部分代码省略.........
开发者ID:goura,项目名称:karesansui,代码行数:103,代码来源:iptables.py

示例10: len

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
            if old_ret is True and len(old_lines) != 0:
                self.do_lint("\n".join(old_lines),lint=False)
            elif old_ret is False:
                self.do_stop()

        return retval

"""
"""
if __name__ == '__main__':
    """Testing
    """
    parser = iptablesParser()
    dop = DictOp()
    dop.addconf("dum",parser.read_conf())
    lines = dop.get("dum",['config'])
    lines.append("aa# test")
    lines.append("bb# test")
    lines.append("aa# test")
    #preprint_r(lines)

    dop.set("dum",['config'],lines)
    conf = dop.getconf("dum")
    #preprint_r(conf)

    parser.do_stop()
    print parser.is_running()
    parser.do_start()
    print parser.is_running()
    parser.do_stop()
    print parser.is_running()
开发者ID:goura,项目名称:karesansui,代码行数:33,代码来源:iptables.py

示例11: iptablesParser

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import get [as 别名]
                self.do_lint("\n".join(old_lines), lint=False)
            elif old_ret is False:
                self.do_stop()

        return retval


"""
"""
if __name__ == "__main__":
    """Testing
    """
    parser = iptablesParser()
    dop = DictOp()
    dop.addconf("dum", parser.read_conf())
    lines = dop.get("dum", ["config"])
    lines.append("aa# test")
    lines.append("bb# test")
    lines.append("aa# test")
    # preprint_r(lines)

    dop.set("dum", ["config"], lines)
    conf = dop.getconf("dum")
    # preprint_r(conf)

    parser.do_stop()
    print parser.is_running()
    parser.do_start()
    print parser.is_running()
    parser.do_stop()
    print parser.is_running()
开发者ID:nabeken,项目名称:karesansui,代码行数:33,代码来源:iptables.py


注:本文中的karesansui.lib.dict_op.DictOp.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。