本文整理汇总了Python中augeas.Augeas.save方法的典型用法代码示例。如果您正苦于以下问题:Python Augeas.save方法的具体用法?Python Augeas.save怎么用?Python Augeas.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类augeas.Augeas
的用法示例。
在下文中一共展示了Augeas.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: configure_chrony
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def configure_chrony(ntp_servers, ntp_pool=None,
fstore=None, sysstore=None, debug=False):
"""
This method only configures chrony client with ntp_servers or ntp_pool
"""
module = "chrony"
if sysstore:
sysstore.backup_state(module, "enabled",
services.knownservices.chronyd.is_enabled())
aug = Augeas(flags=Augeas.NO_LOAD | Augeas.NO_MODL_AUTOLOAD,
loadpath=paths.USR_SHARE_IPA_DIR)
try:
logger.debug("Configuring chrony")
chrony_conf = os.path.abspath(paths.CHRONY_CONF)
aug.transform(module, chrony_conf) # loads chrony lens file
aug.load() # loads augeas tree
# augeas needs to prepend path with '/files'
path = '/files{path}'.format(path=chrony_conf)
# remove possible conflicting configuration of servers
aug.remove('{}/server'.format(path))
aug.remove('{}/pool'.format(path))
aug.remove('{}/peer'.format(path))
if ntp_pool:
logger.debug("Setting server pool:")
logger.debug("'%s'", ntp_pool)
aug.set('{}/pool[last()+1]'.format(path), ntp_pool)
aug.set('{}/pool[last()]/iburst'.format(path), None)
if ntp_servers:
logger.debug("Setting time servers:")
for server in ntp_servers:
aug.set('{}/server[last()+1]'.format(path), server)
aug.set('{}/server[last()]/iburst'.format(path), None)
logger.debug("'%s'", server)
# backup oginal conf file
logger.debug("Backing up '%s'", chrony_conf)
__backup_config(chrony_conf, fstore)
logger.debug("Writing configuration to '%s'", chrony_conf)
aug.save()
logger.info('Configuration of chrony was changed by installer.')
configured = True
except IOError:
logger.error("Augeas failed to configure file %s", chrony_conf)
configured = False
except RuntimeError as e:
logger.error("Configuration failed with: %s", e)
configured = False
finally:
aug.close()
tasks.restore_context(chrony_conf)
return configured
示例2: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
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
示例3: remove
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
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
示例4: set
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
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 }
示例5: remove
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
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
示例6: rm
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def rm(self,entryPath,param='',hierarchy='/files'):
"""Delete a parameter (and all its children) 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:
result=aug.remove(path)
#aug.close()
except Exception, e: return str(e)
# Here is a little workaround for a bug in save for augeas.
# In the future this should not be necessary anymore.
try:
aug.save()
except:
pass
# End of workaround
try:
aug.save()
except Exception, e: return str(e)
if result == -1:
msg = 'Invalid node'
else:
msg = repr(result)+' node(s) removed.'
return msg
示例7: SysConfig
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
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
示例8: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
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
示例9: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def setvalue(name, expressions):
ret = {"name": name, "result": True, "changes": {}, "comment": "No changes made"}
from augeas import Augeas
if len(expressions) < 1:
ret["comment"] = "No expressions given"
ret["result"] = False
return ret
if __opts__["test"]:
aug = Augeas(flags=Augeas.SAVE_NEWFILE)
sfn = name
dfn = "%s.augnew" % name
else:
aug = Augeas(flags=Augeas.SAVE_BACKUP)
sfn = "%s.augsave" % name
dfn = name
if not os.path.isfile(name):
ret["comment"] = "Unable to find file '%s'" % name
ret["result"] = False
return ret
for (subpath, value) in expressions:
try:
path = "/files%s/%s" % (name, subpath)
aug.set(path, value)
except ValueError as e:
ret["comment"] = '%s for\n"%s" = "%s"' % (e, path, value)
ret["result"] = False
return ret
except TypeError as e:
ret["comment"] = (
"Error setting values:\n" "%s\n" "Expression was '%s' '%s'\n" "Try quoting the value" % (e, path, value)
)
ret["result"] = False
return ret
except e:
ret["comment"] = "Unknown error:\n%s" % e
ret["result"] = False
return ret
try:
aug.save()
except IOError as e:
ret["comment"] = str(e)
ret["result"] = False
return ret
ret.update(_resolve_changes(sfn, dfn))
return ret
示例10: execute
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def execute(*args, **kw):
if conf.timezone == None:
print >> sys.stderr, utils.multiline_message(
_("""
Please supply the timezone PHP should be using.
You have to use a Continent or Country / City locality name
like 'Europe/Berlin', but not just 'CEST'.
""")
)
conf.timezone = utils.ask_question(
_("Timezone ID"),
default="UTC"
)
if not conf.php_ini_path == None:
if not os.path.isfile(conf.php_ini_path):
log.error(_("Cannot configure PHP through %r (No such file or directory)") % (conf.php_ini_path))
return
php_ini = conf.php_ini_path
else:
# Search and destroy
php_ini = "/etc/php.ini"
if not os.path.isfile(php_ini):
php_ini = "/etc/php5/apache2/php.ini"
if not os.path.isfile(php_ini):
log.error(_("Could not find PHP configuration file php.ini"))
return
myaugeas = Augeas()
setting_base = '/files%s/' % (php_ini)
setting = os.path.join(setting_base, 'Date', 'date.timezone')
current_value = myaugeas.get(setting)
if current_value == None:
insert_paths = myaugeas.match('/files%s/Date/*' % (php_ini))
insert_path = insert_paths[(len(insert_paths)-1)]
myaugeas.insert(insert_path, 'date.timezone', False)
log.debug(_("Setting key %r to %r") % ('Date/date.timezone', conf.timezone), level=8)
myaugeas.set(setting, conf.timezone)
myaugeas.save()
示例11: remove
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def remove(name, values):
ret = {"name": name, "result": True, "changes": {}, "comment": ""}
from augeas import Augeas
if len(values) < 1:
ret["comment"] = "No values given"
ret["result"] = False
return ret
if __opts__["test"]:
aug = Augeas(flags=Augeas.SAVE_NEWFILE)
sfn = name
dfn = "%s.augnew" % name
else:
aug = Augeas(flags=Augeas.SAVE_BACKUP)
sfn = "%s.augsave" % name
dfn = name
if not os.path.isfile(name):
ret["comment"] = "Unable to find file '%s'" % name
ret["result"] = False
return ret
for value in values:
try:
path = "/files%s/%s" % (name, value)
aug.remove(path)
except TypeError as e:
ret["comment"] = "Error removing, wrong type\n" "Expression was '%s'" % path
ret["result"] = False
return ret
try:
aug.save()
except IOError as e:
ret["comment"] = str(e)
ret["result"] = False
return ret
ret.update(_resolve_changes(sfn, dfn))
return ret
示例12: set_api_timeouts
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def set_api_timeouts(self, timeout):
# Determine the file to change
if self.https:
config_file = self.abiquo_ssl_conf
else:
config_file = self.abiquo_conf
logging.info("Setting Proxy timeouts in %s" % config_file)
# Set timeout using Augeas
a = Augeas()
for loc in a.match("/files%s/VirtualHost/*[arg='/api']" % config_file):
proxy_pass = a.match("%s/*[self::directive='ProxyPass']" % loc)
if len(proxy_pass) == 1:
# Proxy timeout already exists
logging.info("ProxyPass found")
arg1 = a.get("%s/arg" % proxy_pass[0])
arg2 = "timeout=%s" % timeout
a.set("%s/arg[1]" % proxy_pass[0], arg1)
a.set("%s/arg[2]" % proxy_pass[0], arg2)
a.save()
a.close()
示例13: __disable_mod_ssl_ocsp
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def __disable_mod_ssl_ocsp(self):
aug = Augeas(flags=Augeas.NO_LOAD | Augeas.NO_MODL_AUTOLOAD)
aug.set('/augeas/load/Httpd/lens', 'Httpd.lns')
aug.set('/augeas/load/Httpd/incl', paths.HTTPD_SSL_CONF)
aug.load()
path = '/files{}/VirtualHost'.format(paths.HTTPD_SSL_CONF)
ocsp_path = '{}/directive[.="{}"]'.format(path, OCSP_DIRECTIVE)
ocsp_arg = '{}/arg'.format(ocsp_path)
ocsp_comment = '{}/#comment[.="{}"]'.format(path, OCSP_DIRECTIVE)
ocsp_dir = aug.get(ocsp_path)
# there is SSLOCSPEnable directive in nss.conf file, comment it
# otherwise just do nothing
if ocsp_dir is not None:
ocsp_state = aug.get(ocsp_arg)
aug.remove(ocsp_arg)
aug.rename(ocsp_path, '#comment')
aug.set(ocsp_comment, '{} {}'.format(OCSP_DIRECTIVE, ocsp_state))
aug.save()
示例14: LVMConfig
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
class LVMConfig(object):
def __init__(self, path="/etc/lvm/lvm.conf"):
self.path = path
# Augeas loads by default tons of unneeded lenses and configuration
# files. On my test host, it fails to load, trying to read my 500 MiB
# /etc/lvm/archive/.
#
# These are the standard LVM lens includes:
# /augeas/load/LVM/incl[1] /etc/lvm/lvm.conf
# /augeas/load/LVM/incl[2] /etc/lvm/backup/*
# /augeas/load/LVM/incl[3] /etc/lvm/archive/*.vg
#
# We need only the first entry to work with lvm.conf. Using customized
# load setup, as explained in
# https://github.com/hercules-team/augeas/wiki/Loading-specific-files
#
# Removing the archive and backup entries, we can load augeas in 0.7
# seconds on my test vm. Removing all other lenses shorten the time to
# 0.04 seconds.
log.debug("Loading LVM configuration from %r", path)
self.aug = Augeas(flags=Augeas.NO_MODL_AUTOLOAD | Augeas.SAVE_BACKUP)
self.aug.add_transform("lvm.lns", [path])
self.aug.load()
# Context manager interface
def __enter__(self):
return self
def __exit__(self, t, v, tb):
try:
self.close()
except Exception as e:
# Caller succeeded, raise the close error.
if t is None:
raise
# Caller has failed, do not hide the original error.
log.exception("Error closing %s: %s" % (self, e))
# Accessing list of strings
def getlist(self, section, option):
pat = "/files%s/%s/dict/%s/list/*/str" % (self.path, section, option)
matches = self.aug.match(pat)
if not matches:
return None # Cannot store/read empty list
return [self.aug.get(m) for m in matches]
def setlist(self, section, option, value):
log.debug("Setting %s/%s to %s", section, option, value)
opt_path = "/files%s/%s/dict/%s" % (self.path, section, option)
self.aug.remove(opt_path)
item_path = opt_path + "/list/%d/str"
for i, item in enumerate(value, 1):
self.aug.set(item_path % i, item)
# Accessing flat values (int, string)
def getint(self, section, option):
val = self._get_flat(section, option, "int")
return int(val) if val is not None else None
def setint(self, section, option, value):
self._set_flat(section, option, "int", str(value))
def getstr(self, section, option):
return self._get_flat(section, option, "str")
def setstr(self, section, option, value):
self._set_flat(section, option, "str", value)
def _get_flat(self, section, option, opt_type):
path = self._flat_path(section, option, opt_type)
return self.aug.get(path)
def _set_flat(self, section, option, opt_type, value):
log.debug("Setting %s/%s to %r", section, option, value)
path = self._flat_path(section, option, opt_type)
return self.aug.set(path, value)
def _flat_path(self, section, option, opt_type):
return "/files%s/%s/dict/%s/%s" % (
self.path, section, option, opt_type)
# Removing options
def remove(self, section, option):
log.debug("Removing %s/%s", section, option)
path = "/files%s/%s/dict/%s" % (self.path, section, option)
self.aug.remove(path)
# File operations
def save(self):
log.info("Saving new LVM configuration to %r, previous configuration "
"saved to %r",
self.path, self.path + ".augsave")
#.........这里部分代码省略.........
示例15: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import save [as 别名]
def setvalue(*args):
'''
Set a value for a specific augeas path
CLI Example:
.. code-block:: bash
salt '*' augeas.setvalue /files/etc/hosts/1/canonical localhost
This will set the first entry in /etc/hosts to localhost
CLI Example:
.. code-block:: bash
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:
.. code-block:: bash
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:
if len(prefix) > 1:
raise SaltInvocationError(
'Only one \'prefix=\' value is permitted'
)
else:
prefix = prefix[0].split('=', 1)[1]
if len(tuples) % 2 != 0:
raise SaltInvocationError('Uneven number of path/value arguments')
tuple_iter = iter(tuples)
for path, value in zip(tuple_iter, tuple_iter):
target_path = path
if prefix:
target_path = os.path.join(prefix.rstrip('/'), path.lstrip('/'))
try:
aug.set(target_path, str(value))
except ValueError as err:
ret['error'] = 'Multiple values: {0}'.format(err)
try:
aug.save()
ret['retval'] = True
except IOError as err:
ret['error'] = str(err)
return ret