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


Python augeas.Augeas类代码示例

本文整理汇总了Python中augeas.Augeas的典型用法代码示例。如果您正苦于以下问题:Python Augeas类的具体用法?Python Augeas怎么用?Python Augeas使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: setvalue

def setvalue(*args):
    '''
    Set a value for a specific augeas path

    CLI Example::

        salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost

    This will set the first entry in /etc/hosts to localhost

    CLI Example::

        salt '*' augeas.setvalue /files/etc/hosts/01/ipaddr 192.168.1.1 \\
                                 /files/etc/hosts/01/canonical test

    Adds a new host to /etc/hosts the ip address 192.168.1.1 and hostname test

    CLI Example::

        salt '*' augeas.setvalue prefix=/files/etc/sudoers/ \\
                 "spec[user = '%wheel']/user" "%wheel" \\
                 "spec[user = '%wheel']/host_group/host" 'ALL' \\
                 "spec[user = '%wheel']/host_group/command[1]" 'ALL' \\
                 "spec[user = '%wheel']/host_group/command[1]/tag" 'PASSWD' \\
                 "spec[user = '%wheel']/host_group/command[2]" '/usr/bin/apt-get' \\
                 "spec[user = '%wheel']/host_group/command[2]/tag" NOPASSWD

    Ensures that the following line is present in /etc/sudoers::

        %wheel ALL = PASSWD : ALL , NOPASSWD : /usr/bin/apt-get , /usr/bin/aptitude
    '''
    aug = Augeas()
    ret = {'retval': False}


    tuples = filter(lambda x: not x.startswith('prefix='), args)
    prefix = filter(lambda x: x.startswith('prefix='), args)
    if prefix:
        prefix = prefix[0].split('=', 1)[1]

    if len(tuples) % 2 != 0:
        return ret  # ensure we have multiple of twos

    tuple_iter = iter(tuples)

    for path, value in zip(tuple_iter, tuple_iter):
        target_path = path
        if prefix:
            target_path = "{0}/{1}".format(prefix.rstrip('/'), path.lstrip('/'))
        try:
            aug.set(target_path, str(value))
        except ValueError as err:
            ret['error'] = "Multiple values: " + str(err)

    try:
        aug.save()
        ret['retval'] = True
    except IOError as err:
        ret['error'] = str(err)
    return ret
开发者ID:herlo,项目名称:salt,代码行数:60,代码来源:augeas_cfg.py

示例2: get

def get(path, value=""):
    """
    Get a value for a specific augeas path

    CLI Example::

        salt '*' augeas.get /files/etc/hosts/1/ ipaddr
    """

    from augeas import Augeas

    aug = Augeas()

    ret = {}

    path = path.rstrip("/")
    if value:
        path += "/{0}".format(value.strip("/"))

    try:
        _match = aug.match(path)
    except RuntimeError as err:
        return {"error": str(err)}

    if _match:
        ret[path] = aug.get(path)
    else:
        ret[path] = ""  # node does not exist

    return ret
开发者ID:fatbox,项目名称:salt,代码行数:30,代码来源:augeas_cfg.py

示例3: get

    def get(self,entryPath,param='',hierarchy='/files'):
        """Get a value for a config. parameter in a config. file,
with the help of Augeas, a configuration API (cf http://augeas.net)"""
        try:
            from augeas import Augeas
            aug=Augeas()
        except Exception, e: return str(e)
        # yes, entryPath.rstrip('/')+'/' is really needed (i.e. entryPath=/)
        path=(hierarchy+entryPath.rstrip('/')+'/'+param).rstrip('/')
        try:
            matchtest=aug.match(path) 
        except Exception, e: return str(e)
        if matchtest:
            try:
                pvalue=aug.get(path) 
                #aug.close()
            except Exception, e: return str(e)
        else:
            # The node doesn't exist
            pvalue='(o)'

        if not pvalue:
            # The node doesn't have a value
            pvalue='(none)'

        return { 'path': entryPath, 'parameter': param, 'value': pvalue, 'hierarchy': hierarchy }
开发者ID:Lorquas,项目名称:func,代码行数:26,代码来源:confmgt_augeas.py

示例4: remove

def remove(path):
    """
    Get matches for path expression

    CLI Example::

        salt '*' augeas.remove /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians
    """
    from augeas import Augeas

    aug = Augeas()

    ret = {"retval": False}
    try:
        count = aug.remove(path)
        aug.save()
        if count == -1:
            ret["error"] = "Invalid node"
        else:
            ret["retval"] = True
    except (RuntimeError, IOError) as err:
        ret["error"] = str(err)

    ret["count"] = count

    return ret
开发者ID:fatbox,项目名称:salt,代码行数:26,代码来源:augeas_cfg.py

示例5: match

def match(path, value=''):
    '''
    Get matches for path expression

    CLI Example::

        salt '*' augeas.match /files/etc/services/service-name ssh
    '''

    from augeas import Augeas
    aug = Augeas()

    ret = {}

    try:
        matches = aug.match(path)
    except RuntimeError:
        return ret

    for _match in matches:
        if value and aug.get(_match) == value:
            ret[_match] = value
        elif not value:
            ret[_match] = aug.get(_match)
    return ret
开发者ID:Adapptor,项目名称:salt,代码行数:25,代码来源:augeas_cfg.py

示例6: _libvirt_init_config

def _libvirt_init_config():

    x("yum install augeas -y")
    #Initialize augeas
    augeas = Augeas(x)

    augeas.set_enhanced("/files/etc/sysconfig/libvirt-guests/ON_SHUTDOWN","shutdown")
开发者ID:Nemie,项目名称:syco,代码行数:7,代码来源:installKvmHost.py

示例7: remove

def remove(path):
    '''
    Get matches for path expression

    CLI Example:

    .. code-block:: bash

        salt '*' augeas.remove /files/etc/sysctl.conf/net.ipv4.conf.all.log_martians
    '''
    aug = Augeas()
    ret = {'retval': False}
    try:
        count = aug.remove(path)
        aug.save()
        if count == -1:
            ret['error'] = 'Invalid node'
        else:
            ret['retval'] = True
    except (RuntimeError, IOError) as err:
        ret['error'] = str(err)

    ret['count'] = count

    return ret
开发者ID:sijis,项目名称:salt,代码行数:25,代码来源:augeas_cfg.py

示例8: install_syco

def install_syco(args):
    """
    Install/configure this script on the current computer.

    """
    app.print_verbose("Install syco version: %d" % SCRIPT_VERSION)
    version_obj = version.Version("InstallSYCO", SCRIPT_VERSION)
    version_obj.check_executed()

    #Override base repo to one that works
    x("cat %syum/CentOS-Base.repo > /etc/yum.repos.d/CentOS-Base.repo" % app.SYCO_VAR_PATH)

    #Set Swappiness to 0 on all hosts to avoid excessive swapping
    x('sysctl vm.swappiness=0')

    app.print_verbose("Install required packages for syco")
    x("yum install augeas -y")

    app.print_verbose("Create symlink /sbin/syco")
    set_syco_permissions()
    if not os.path.exists('/sbin/syco'):
        os.symlink('%sbin/syco.py' % SYCO_PATH, '/sbin/syco')

    #Use augeas to set max kernels to 2 since more won't fit on /boot
    from augeas import Augeas
    augeas = Augeas(x)
    augeas.set_enhanced("/files/etc/yum.conf/main/installonly_limit", "2")

    version_obj.mark_executed()
开发者ID:ysoldak,项目名称:syco,代码行数:29,代码来源:installSyco.py

示例9: get

def get(path, value=''):
    '''
    Get a value for a specific augeas path

    CLI Example:

    .. code-block:: bash

        salt '*' augeas.get /files/etc/hosts/1/ ipaddr
    '''
    aug = Augeas()
    ret = {}

    path = path.rstrip('/')
    if value:
        path += '/{0}'.format(value.strip('/'))

    try:
        _match = aug.match(path)
    except RuntimeError as err:
        return {'error': str(err)}

    if _match:
        ret[path] = aug.get(path)
    else:
        ret[path] = ''  # node does not exist

    return ret
开发者ID:sijis,项目名称:salt,代码行数:28,代码来源:augeas_cfg.py

示例10: SysConfig

class SysConfig (object):
    def __init__ (self, system_ip = None, system_id = None, system_type = None):
        """
        Initialize this object with non system related data, like the OSSIM administration IP address.
        """
        self.__system_ip = system_ip if is_ipv4(system_ip) else None
        self.__system_id = system_id
        self.__system_type = system_type

        self.__augeas = Augeas()

        self.__pending = {}

        # System data
        self.__net_ifaces = {}
        self.__hosts_entries = {}

        # Initialize pure system data.
        self.__reload_config__ ()

    #
    # Public methods
    #
    def is_pending (self):
        """
        Are there pending changes?
        """
        return self.__pending != {}

    def get_pending (self):
        """
        Get which changes are pending
        """
        return self.__pending

    def get_pending_str (self):
        """
        Same as get_pending(), but in human format.
        """
        data = ''
        for key, value in self.__pending.iteritems():
            data += '\n[%s]\n%s' % (key, value)
        return data

    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))

        self.__pending = {}
        self.__reload_config__ ()
        return AVConfigParserErrors.ALL_OK
开发者ID:AntBean,项目名称:alienvault-ossim,代码行数:59,代码来源:sysconfig.py

示例11: epel_repo

def epel_repo():
    """
    Setup EPEL repository.
    """

    # Check if epel is already installed and enabled
    augeas = Augeas(x)
    epel_enabled = augeas.find_values('/files/etc/yum.repos.d/epel.repo/epel/enabled')
    if len(epel_enabled) != 1 or epel_enabled[0] != '1':
        x("yum install -y epel-release")
        augeas.set_enhanced('/files/etc/yum.repos.d/epel.repo/epel/enabled', '1')
开发者ID:kribor,项目名称:syco,代码行数:11,代码来源:install.py

示例12: setvalue

def setvalue(*args):
    '''
    Set a value for a specific augeas path

    CLI Example::

        salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost

        salt '*' augeas.setvalue /files/etc/hosts/01/ipaddr 192.168.1.1 \
                                 /files/etc/hosts/01/canonical hostname

        salt '*' augeas.setvalue prefix=/files/etc/sudoers/ \
                 "/spec[user = '%wheel']/user" "%wheel" \
                 "/spec[user = '%wheel']/host_group/host" 'ALL' \
                 "/spec[user = '%wheel']/host_group/command[1]" 'ALL' \
                 "/spec[user = '%wheel']/host_group/command[1]/tag" 'PASSWD' \
                 "/spec[user = '%wheel']/host_group/command[2]" '/usr/bin/apt-get' \
                 "/spec[user = '%wheel']/host_group/command[2]/tag" NOPASSWD
    '''


    from augeas import Augeas
    aug = Augeas()

    ret = {'retval': False}

    prefix = None


    tuples = filter(lambda x: not x.startswith('prefix='), args)
    prefix = filter(lambda x: x.startswith('prefix='), args)
    if prefix:
        prefix = prefix[0].split('=', 1)[1]

    if len(tuples) % 2 != 0:
        return ret  # ensure we have multiple of twos

    tuple_iter = iter(tuples)

    for path, value in zip(tuple_iter, tuple_iter):
        target_path = path
        if prefix:
            target_path = "{0}/{1}".format(prefix.rstrip('/'), path.lstrip('/'))
        try:
            aug.set(target_path, str(value))
        except ValueError as err:
            ret['error'] = "Multiple values: " + str(err)

    try:
        aug.save()
        ret['retval'] = True
    except IOError as err:
        ret['error'] = str(err)
    return ret
开发者ID:Adapptor,项目名称:salt,代码行数:54,代码来源:augeas_cfg.py

示例13: get_configured_ifaces

def get_configured_ifaces():
    aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD)
    aug.add_transform('interfaces', '/etc/network/interfaces')
    aug.load()
    base = '/files/etc/network/interfaces'
    for m in aug.match('%s/iface' % base):
        yield aug.get(m)
    aug.close()
开发者ID:akatrevorjay,项目名称:solarsan,代码行数:8,代码来源:models.py

示例14: setup_clam_and_freshclam

def setup_clam_and_freshclam():
    #
    # Setup clamav and freshclam
    #
    app.print_verbose("Setup clamav and freshclam")

    app.print_verbose("  Setup config files.")
    x("cp /usr/local/etc/clamd.conf.sample /usr/local/etc/clamd.conf")
    clamd = scOpen("/usr/local/etc/clamd.conf")
    clamd.replace("^[#]\?Example.*",            "#Example")
    clamd.replace("^[#]\?LogFileMaxSize.*",     "LogFileMaxSize 100M")
    clamd.replace("^[#]\?LogFile.*",            "LogFile /var/log/clamav/clamd.log")
    clamd.replace("^[#]\?LogTime.*",            "LogTime yes")
    clamd.replace("^[#]\?LogSyslog.*",          "LogSyslog yes")
    clamd.replace("^[#]\?TCPSocket.*",          "TCPSocket 3310")
    clamd.replace("^[#]\?TCPAddr.*",            "TCPAddr 127.0.0.1")
    clamd.replace("^[#]\?ExcludePath.*/proc.*", "ExcludePath ^/proc")
    clamd.replace("^[#]\?ExcludePath.*/sys.*",  "ExcludePath ^/sys")
    clamd.replace("^[#]\?User.*",               "User clamav")
    clamd.replace("^[#]\?LocalSocket.*",        "LocalSocket /var/run/clamav/clamd.socket")
    clamd.replace("^[#]\?PidFile.*",            "PidFile /var/run/clamav/clamd.pid")
    clamd.replace("^[#]\?DatabaseDirectory.*",  "DatabaseDirectory /var/lib/clamav")

    x("cp /usr/local/etc/freshclam.conf.sample /usr/local/etc/freshclam.conf")
    freshclam = scOpen("/usr/local/etc/freshclam.conf")
    freshclam.replace("^[#]\?Example.*",        "#Example")
    freshclam.replace("^[#]\?LogFileMaxSize.*", "LogFileMaxSize 100M")
    freshclam.replace("^[#]\?LogTime.*",        "LogTime yes")
    freshclam.replace("^[#]\?LogSyslog.*",      "LogSyslog yes")
    freshclam.replace("^[#]\?DatabaseOwner.*",  "DatabaseOwner clamav")
    freshclam.replace("^[#]\?PidFile.*",        "PidFile /var/run/clamav/freshclam.pid")
    freshclam.replace("^[#]\?DatabaseMirror.*", "DatabaseMirror db.northeu.clamav.net")
    freshclam.replace("^[#]\?UpdateLogFile.*",  "UpdateLogFile /var/log/clamav/freshclam.log")
    freshclam.replace("^[#]\?DatabaseDirectory.*", "DatabaseDirectory /var/lib/clamav")

    #TODO: Change replace statements above to augeas since that tends to be more stable.
    app.print_verbose("  Install augeas and add clam lens that is not available on CentOS 6")
    x("yum install -y augeas")
    x("cp %s/augeas/lenses/clamav.aug /usr/share/augeas/lenses/dist/" % app.SYCO_VAR_PATH)

    #Help augeas find freshclam.conf
    if x("readlink /etc/freshclam.conf").find("/usr/local/etc/freshclam.conf") == -1:
        x("rm -f /etc/freshclam.conf")
        x("ln -s /usr/local/etc/freshclam.conf /etc/")

    #Initialize augeas
    augeas = Augeas(x)

    if config.general.get_proxy_host() and config.general.get_proxy_port():
        app.print_verbose("  Configure proxy for freshclam")
        augeas.set_enhanced("/files/etc/freshclam.conf/HTTPProxyPort", "%s" % config.general.get_proxy_port())
        augeas.set_enhanced("/files/etc/freshclam.conf/HTTPProxyServer", "%s" % config.general.get_proxy_host())
开发者ID:arlukin,项目名称:syco,代码行数:52,代码来源:installClam.py

示例15: set

    def set(self,entryPath,param='',pvalue='',hierarchy='/files'):
        """Set/change a value for a config. parameter in a config. file,
with the help of Augeas, a configuration API (cf http://augeas.net)"""
        try:
            from augeas import Augeas
            aug=Augeas()
        except Exception, e: return str(e)

        path=(hierarchy+entryPath.rstrip('/')+'/'+param).rstrip('/')

        try:
            aug.set(path,pvalue)
        except Exception, e: return str(e)
        # Here is a little workaround for a bug in save for augeas.
        # In the future this won't be necessary anymore.
        try:
            aug.save()
        except:
            pass
        # End of workaround
        try:
            aug.save()
        except Exception, e: return str(e)

        try:
            pvalue=aug.get(path)
            #aug.close()
        except Exception, e: return str(e)

        return { 'path': entryPath, 'parameter': param, 'value': pvalue, 'hierarchy': hierarchy  }
开发者ID:Lorquas,项目名称:func,代码行数:30,代码来源:confmgt_augeas.py


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