本文整理汇总了Python中augeas.Augeas.set方法的典型用法代码示例。如果您正苦于以下问题:Python Augeas.set方法的具体用法?Python Augeas.set怎么用?Python Augeas.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类augeas.Augeas
的用法示例。
在下文中一共展示了Augeas.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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 }
示例2: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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
示例4: _augeas_init
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [as 别名]
def _augeas_init():
if not _directories_inited:
init_directories()
global augeas
augeas = Augeas(loadpath=get_config_path(),
flags=Augeas.SAVE_BACKUP | Augeas.NO_MODL_AUTOLOAD)
augeas.set("/augeas/load/Agocontrol/lens", "agocontrol.lns");
augeas.set("/augeas/load/Agocontrol/incl[1]", get_config_path("conf.d") + "/*.conf");
augeas.load()
示例5: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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
示例6: configure_chrony
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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
示例7: execute
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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()
示例8: get_augeas
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [as 别名]
def get_augeas(self, entry):
""" Get an augeas object for the given entry. """
if entry.get("name") not in self._augeas:
aug = Augeas()
if entry.get("lens"):
self.logger.debug("Augeas: Adding %s to include path for %s" %
(entry.get("name"), entry.get("lens")))
incl = "/augeas/load/%s/incl" % entry.get("lens")
ilen = len(aug.match(incl))
if ilen == 0:
self.logger.error("Augeas: Lens %s does not exist" %
entry.get("lens"))
else:
aug.set("%s[%s]" % (incl, ilen + 1), entry.get("name"))
aug.load()
self._augeas[entry.get("name")] = aug
return self._augeas[entry.get("name")]
示例9: set_api_timeouts
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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()
示例10: __disable_mod_ssl_ocsp
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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()
示例11: Augeas
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [as 别名]
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. A copy of the GNU General Public License is
# also available at http://www.gnu.org/copyleft/gpl.html.
from ovirt.node import base
from ovirt.node.utils.fs import Config
from augeas import Augeas
import os
aug_unwrapped = Augeas()
aug_unwrapped.set("/augeas/save/copy_if_rename_fails", "")
class ConfigMigrationRunner(base.Base):
def run_if_necessary(self):
"""Migrate the configs if needed
"""
migration_func = self._determine_migration_func()
if migration_func:
self._run(migration_func)
else:
self.logger.debug("No config migration needed")
def _determine_migration_func(self):
"""Determins if a migration and which migration is necessary
示例12: LVMConfig
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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")
#.........这里部分代码省略.........
示例13: setvalue
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [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
示例14: execute
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [as 别名]
#.........这里部分代码省略.........
search_base = %(base_dn)s
scope = sub
domain = ldap:/etc/postfix/ldap/mydestination.cf
bind_dn = %(service_bind_dn)s
bind_pw = %(service_bind_pw)s
query_filter = (&(|(mail=%%s)(alias=%%s))(objectclass=kolabsharedfolder)(kolabFolderType=mail))
result_attribute = kolabtargetfolder
result_format = shared+%%s
""" % {
"base_dn": conf.get('ldap', 'base_dn'),
"server_host": server_host,
"service_bind_dn": conf.get('ldap', 'service_bind_dn'),
"service_bind_pw": conf.get('ldap', 'service_bind_pw'),
},
}
if not os.path.isdir('/etc/postfix/ldap'):
os.mkdir('/etc/postfix/ldap/', 0770)
for filename in files.keys():
fp = open(filename, 'w')
fp.write(files[filename])
fp.close()
fp = open('/etc/postfix/transport', 'a')
fp.write("\n# Shared Folder Delivery for %(domain)s:\[email protected]%(domain)s\t\tlmtp:unix:/var/lib/imap/socket/lmtp\n" % {'domain': conf.get('kolab', 'primary_domain')})
fp.close()
subprocess.call(["postmap", "/etc/postfix/transport"])
postfix_main_settings = {
"inet_interfaces": "all",
"recipient_delimiter": "+",
"local_recipient_maps": "ldap:/etc/postfix/ldap/local_recipient_maps.cf",
"mydestination": "ldap:/etc/postfix/ldap/mydestination.cf",
"transport_maps": "ldap:/etc/postfix/ldap/transport_maps.cf, hash:/etc/postfix/transport",
"virtual_alias_maps": "$alias_maps, ldap:/etc/postfix/ldap/virtual_alias_maps.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_mailforwarding.cf, ldap:/etc/postfix/ldap/virtual_alias_maps_sharedfolders.cf, ldap:/etc/postfix/ldap/mailenabled_distgroups.cf, ldap:/etc/postfix/ldap/mailenabled_dynamic_distgroups.cf",
"smtpd_tls_auth_only": "yes",
"smtpd_tls_security_level": "may",
"smtp_tls_security_level": "may",
"smtpd_sasl_auth_enable": "yes",
"smtpd_sender_login_maps": "$local_recipient_maps",
"smtpd_sender_restrictions": "permit_mynetworks, reject_sender_login_mismatch",
"smtpd_recipient_restrictions": "permit_mynetworks, reject_unauth_pipelining, reject_rbl_client zen.spamhaus.org, reject_non_fqdn_recipient, reject_invalid_helo_hostname, reject_unknown_recipient_domain, reject_unauth_destination, check_policy_service unix:private/recipient_policy_incoming, permit",
"smtpd_sender_restrictions": "permit_mynetworks, check_policy_service unix:private/sender_policy_incoming",
"submission_recipient_restrictions": "check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
"submission_sender_restrictions": "reject_non_fqdn_sender, check_policy_service unix:private/submission_policy, permit_sasl_authenticated, reject",
"submission_data_restrictions": "check_policy_service unix:private/submission_policy",
"content_filter": "smtp-amavis:[127.0.0.1]:10024"
}
if os.path.isfile('/etc/pki/tls/certs/make-dummy-cert') and not os.path.isfile('/etc/pki/tls/private/localhost.pem'):
subprocess.call(['/etc/pki/tls/certs/make-dummy-cert', '/etc/pki/tls/private/localhost.pem'])
if os.path.isfile('/etc/pki/tls/private/localhost.pem'):
postfix_main_settings['smtpd_tls_cert_file'] = "/etc/pki/tls/private/localhost.pem"
postfix_main_settings['smtpd_tls_key_file'] = "/etc/pki/tls/private/localhost.pem"
if not os.path.isfile('/etc/postfix/main.cf'):
if os.path.isfile('/usr/share/postfix/main.cf.debian'):
shutil.copy(
'/usr/share/postfix/main.cf.debian',
示例15: install_mail_server
# 需要导入模块: from augeas import Augeas [as 别名]
# 或者: from augeas.Augeas import set [as 别名]
def install_mail_server(args):
"""
Installs a postfix-based mail relay MTA that listens on the DMZ, and relays
towards the internet. Also possible to send from localhost. Also installs mailx.
"""
version_obj = version.Version("Install-postfix-server", SCRIPT_VERSION)
version_obj.check_executed()
app.print_verbose("Installing postfix-server version: {0}".format(SCRIPT_VERSION))
init_properties = PostFixProperties()
# Install required packages
x("yum install -y postfix augeas")
#Initialize augeas
augeas = Augeas(x)
# Set config file parameters
#
general.use_original_file("/etc/postfix/main.cf")
postfix_main_cf = scopen.scOpen("/etc/postfix/main.cf")
# Hostname is full canonical name of machine.
postfix_main_cf.replace("#myhostname = host.domain.tld", "myhostname = {0}".format(config.general.get_mail_relay_domain_name())) # mailrelay.syco.com
postfix_main_cf.replace("#mydomain = domain.tld", "mydomain = {0}".format(config.general.get_resolv_domain())) # syco.com
postfix_main_cf.replace("#myorigin = $mydomain", "myorigin = $myhostname")
# Accept email from all IP addresses for this server
augeas.set_enhanced("/files/etc/postfix/main.cf/inet_interfaces", ",".join(init_properties.server_ips))
#Allow networks
augeas.set_enhanced("/files/etc/postfix/main.cf/mynetworks", ",".join(init_properties.server_networks))
# Do not relay anywhere special, i.e straight to internet.
postfix_main_cf.replace("#relay_domains = $mydestination", "relay_domains =")
postfix_main_cf.replace("#home_mailbox = Maildir/", "home_mailbox = Maildir/")
# Stop warning about IPv6.
postfix_main_cf.replace("inet_protocols = all", "inet_protocols = ipv4")
#Set virtual_alias_maps and virtual_alias_domains in main.cf
augeas.set("/files/etc/postfix/main.cf/virtual_alias_maps", "hash:/etc/postfix/virtual")
if init_properties.virtual_alias_domains:
augeas.set("/files/etc/postfix/main.cf/virtual_alias_domains", init_properties.virtual_alias_domains)
#Add virtual aliases if they do not already exist
for virt_alias_from, virt_alias_to in init_properties.virtual_aliases.iteritems():
existing = augeas.find_entries("/files/etc/postfix/virtual/pattern[. = '%s']" % virt_alias_from)
if len(existing) == 0:
x("echo \"%s %s\" >> /etc/postfix/virtual" % (virt_alias_from, virt_alias_to))
else:
augeas.set_enhanced("/files/etc/postfix/virtual/pattern[. = '%s']/destination" % virt_alias_from,
virt_alias_to)
if len(init_properties.virtual_aliases) > 0:
x("postmap /etc/postfix/virtual")
# Install a simple mail CLI-tool
install_mailx()
# Tell iptables and nrpe that this server is configured as a mail-relay server.
iptables.add_mail_relay_chain()
iptables.save()
x("service postfix restart")
# Send test mail to the syco admin
# and to any virtual alias emails
send_test_mail((None, config.general.get_admin_email()),
init_properties.virtual_aliases.keys())