本文整理汇总了Python中selinux.is_selinux_enabled函数的典型用法代码示例。如果您正苦于以下问题:Python is_selinux_enabled函数的具体用法?Python is_selinux_enabled怎么用?Python is_selinux_enabled使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_selinux_enabled函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: updateGeoRepKeys
def updateGeoRepKeys(userName, geoRepPubKeys):
try:
userInfo = getpwnam(userName)
homeDir = userInfo[5]
uid = userInfo[2]
gid = userInfo[3]
except KeyError as e:
raise ge.GlusterGeoRepUserNotFoundException(err=[str(e)])
sshDir = homeDir + "/.ssh"
authKeysFile = sshDir + "/authorized_keys"
if not os.path.exists(sshDir):
try:
os.makedirs(sshDir, 0o700)
os.chown(sshDir, uid, gid)
if selinux.is_selinux_enabled():
selinux.restorecon(sshDir)
except OSError as e:
raise ge.GlusterGeoRepPublicKeyWriteFailedException(err=[str(e)])
newKeys = [" ".join(l.split()[:-1]) for l in geoRepPubKeys]
newKeyDict = dict(zip(newKeys, geoRepPubKeys))
try:
with open(authKeysFile) as f:
existingKeyLines = f.readlines()
except IOError as e:
if e.errno == errno.ENOENT:
existingKeyLines = []
else:
raise ge.GlusterGeoRepPublicKeyWriteFailedException(err=[str(e)])
try:
existingKeys = [" ".join(l.split()[:-1]) for l in existingKeyLines]
existingKeyDict = dict(zip(existingKeys, existingKeyLines))
outLines = existingKeyLines
outKeys = set(newKeyDict).difference(set(existingKeyDict))
outLines.extend([newKeyDict[k] for k in outKeys if newKeyDict[k]])
safeWrite(authKeysFile, ''.join(outLines))
os.chmod(authKeysFile, 0o600)
os.chown(authKeysFile, uid, gid)
if selinux.is_selinux_enabled():
selinux.restorecon(authKeysFile)
except (IOError, OSError) as e:
raise ge.GlusterGeoRepPublicKeyWriteFailedException(err=[str(e)])
开发者ID:kanalun,项目名称:vdsm,代码行数:48,代码来源:api.py
示例2: diff
def diff(self, file_struct):
self._validate_struct(file_struct)
temp_file, temp_dirs = self.process(file_struct)
path = file_struct['path']
sectx_result = ''
result = ''
try:
cur_sectx = lgetfilecon(path)[1]
except OSError: # workarounding BZ 690238
cur_sectx = None
if not is_selinux_enabled():
cur_sectx = None
if cur_sectx == None:
cur_sectx = ''
if file_struct.has_key('selinux_ctx') and file_struct['selinux_ctx']:
if cur_sectx != file_struct['selinux_ctx']:
sectx_result = "SELinux contexts differ: actual: [%s], expected: [%s]\n" % (cur_sectx, file_struct['selinux_ctx'])
if file_struct['filetype'] == 'symlink':
try:
curlink = os.readlink(path)
newlink = os.readlink(temp_file)
if curlink == newlink:
result = ''
else:
result = "Link targets differ for [%s]: actual: [%s], expected: [%s]\n" % (path, curlink, newlink)
except OSError, e:
if e.errno == 22:
result = "Deployed symlink is no longer a symlink!"
else:
raise e
开发者ID:glubbered,项目名称:spacewalk,代码行数:35,代码来源:file_utils.py
示例3: selinux_enabled
def selinux_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
开发者ID:Anettles123,项目名称:battleschool,代码行数:7,代码来源:ansible_module_dynamic.py
示例4: __init__
def __init__(self):
self.tabs = []
self.xml = xml
xml.signal_connect("on_quit_activate", self.destroy)
xml.signal_connect("on_delete_clicked", self.delete)
xml.signal_connect("on_add_clicked", self.add)
xml.signal_connect("on_properties_clicked", self.properties)
xml.signal_connect("on_local_clicked", self.on_local_clicked)
self.add_page(statusPage.statusPage(xml))
if selinux.is_selinux_enabled() > 0:
try:
self.add_page(booleansPage.booleansPage(xml))
self.add_page(fcontextPage.fcontextPage(xml))
self.add_page(loginsPage.loginsPage(xml))
self.add_page(usersPage.usersPage(xml))
self.add_page(portsPage.portsPage(xml))
self.add_page(modulesPage.modulesPage(xml)) # modules
self.add_page(domainsPage.domainsPage(xml)) # domains
except ValueError as e:
self.error(e.message)
xml.signal_connect("on_quit_activate", self.destroy)
xml.signal_connect("on_policy_activate", self.policy)
xml.signal_connect("on_logging_activate", self.logging)
xml.signal_connect("on_about_activate", self.on_about_activate)
self.add_menu = xml.get_widget("add_menu_item")
self.properties_menu = xml.get_widget("properties_menu_item")
self.delete_menu = xml.get_widget("delete_menu_item")
开发者ID:Chainfire,项目名称:selinux,代码行数:29,代码来源:system-config-selinux.py
示例5: read_cmdline
def read_cmdline(self):
for f in ("selinux", "debug", "leavebootorder", "testing", "extlinux",
"nombr", "gpt", "noefi"):
self.set_cmdline_bool(f)
if not selinux.is_selinux_enabled():
self.selinux = 0
开发者ID:KosiehBarter,项目名称:anaconda,代码行数:7,代码来源:flags.py
示例6: symlink_atomically
def symlink_atomically(srcpath, dstpath, force=False, preserve_context=True):
"""Create a symlink, optionally replacing dstpath atomically, optionally
setting or preserving SELinux context."""
dstdname = os.path.dirname(dstpath)
dstbname = os.path.basename(dstpath)
run_restorecon = False
ctx = None
if preserve_context and selinux.is_selinux_enabled() <= 0:
preserve_context = False
else:
try:
ret, ctx = selinux.lgetfilecon(dstpath)
if ret < 0:
raise RuntimeError("getfilecon(%r) failed" % dstpath)
except OSError as e:
if e.errno == errno.ENOENT:
run_restorecon = True
else:
raise
if not force:
os.symlink(srcpath, dstpath)
if preserve_context:
selinux.restorecon(dstpath)
else:
dsttmp = None
for attempt in range(tempfile.TMP_MAX):
_dsttmp = tempfile.mktemp(
prefix=dstbname + os.extsep, dir=dstdname)
try:
os.symlink(srcpath, _dsttmp)
except OSError as e:
if e.errno == errno.EEXIST:
# try again
continue
raise
else:
dsttmp = _dsttmp
break
if dsttmp is None:
raise IOError(
errno.EEXIST,
"No suitable temporary symlink could be created.")
if preserve_context and not run_restorecon:
selinux.lsetfilecon(dsttmp, ctx)
try:
os.rename(dsttmp, dstpath)
except:
# clean up
os.remove(dsttmp)
raise
if run_restorecon:
selinux.restorecon(dstpath)
开发者ID:cnsnyder,项目名称:python-slip,代码行数:60,代码来源:files.py
示例7: run
def run(options={}):
"""main loop for this plugin"""
_success = 1
_message = 'toggle unsuccessful, selinux setting unchanged'
if 'dryrun' in options:
if options['dryrun'] == True:
_success = 0
_message = 'I would have toggled selinux enforcing setting'
return _success, _message
# First, is SELinux available on this system?
if selinux.is_selinux_enabled():
try:
is_enforce = selinux.security_getenforce()
except OSError:
_success, _message = 1, 'SELinux is not available on this host'
return _success, _message
else:
print 'selinux disabled, will not be able to toggle setting'
sys.exit(1)
_success, _message = toggle_selinux(is_enforce)
return _success, _message
开发者ID:weaselkeeper,项目名称:UsefulIdiot,代码行数:25,代码来源:toggle_selinux.py
示例8: get_current_mode
def get_current_mode(self):
if selinux.is_selinux_enabled():
if selinux.security_getenforce() > 0:
return ENFORCING
else:
return PERMISSIVE
else:
return DISABLED
开发者ID:HotIceCream,项目名称:selinuxuserspace,代码行数:8,代码来源:statusPage.py
示例9: default_container_context
def default_container_context():
if selinux.is_selinux_enabled() != 0:
fd = open(selinux.selinux_lxc_contexts_path())
for i in fd.readlines():
name, context = i.split("=")
if name.strip() == "file":
return context.strip("\n\" ")
return ""
开发者ID:tuxdna,项目名称:atomic,代码行数:8,代码来源:util.py
示例10: main
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True),
persistent=dict(type='bool', default=False),
state=dict(type='bool', required=True),
),
supports_check_mode=True,
)
if not HAVE_SELINUX:
module.fail_json(msg="This module requires libselinux-python support")
if not HAVE_SEMANAGE:
module.fail_json(msg="This module requires libsemanage-python support")
if not selinux.is_selinux_enabled():
module.fail_json(msg="SELinux is disabled on this host.")
name = module.params['name']
persistent = module.params['persistent']
state = module.params['state']
result = dict(
name=name,
)
if hasattr(selinux, 'selinux_boolean_sub'):
# selinux_boolean_sub allows sites to rename a boolean and alias the old name
# Feature only available in selinux library since 2012.
name = selinux.selinux_boolean_sub(name)
if not has_boolean_value(module, name):
module.fail_json(msg="SELinux boolean %s does not exist." % name)
cur_value = get_boolean_value(module, name)
if cur_value == state:
module.exit_json(changed=False, state=cur_value, **result)
if module.check_mode:
module.exit_json(changed=True)
if persistent:
r = semanage_boolean_value(module, name, state)
else:
r = set_boolean_value(module, name, state)
result['changed'] = r
if not r:
module.fail_json(msg="Failed to set boolean %s to %s" % (name, state))
try:
selinux.security_commit_booleans()
except:
module.fail_json(msg="Failed to commit pending boolean %s value" % name)
module.exit_json(**result)
开发者ID:awiddersheim,项目名称:ansible,代码行数:57,代码来源:seboolean.py
示例11: __init__
def __init__(self):
#
# mode of operation
#
self.testing = False
self.debug = False
#
# minor modes
#
self.uevents = False
#
# enable/disable functionality
#
self.selinux = selinux.is_selinux_enabled()
self.multipath = True
self.dmraid = True
self.ibft = True
self.noiswmd = False
self.gfs2 = True
self.jfs = True
self.reiserfs = True
# for this flag to take effect,
# blockdev.mpath.set_friendly_names(flags.multipath_friendly_names) must
# be called prior to calling Blivet.reset() or DeviceTree.populate()
self.multipath_friendly_names = True
# set to False since automatic updates of a device's information
# or state should not be necessary by default
self.auto_dev_updates = False
# set to False by default since a forced reset for file contexts
# is ordinary not necessary
self.selinux_reset_fcon = False
# set to True since we want to keep these around by default
self.keep_empty_ext_partitions = True
# set to False to suppress the default LVM behavior of saving
# backup metadata in /etc/lvm/{archive,backup}
self.lvm_metadata_backup = True
# whether to include nodev filesystems in the devicetree
self.include_nodev = False
# whether to enable discard for newly created devices
# (so far only for LUKS)
self.discard_new = False
self.boot_cmdline = {}
self.update_from_boot_cmdline()
self.allow_imperfect_devices = True
self.debug_threads = False
开发者ID:rhinstaller,项目名称:blivet,代码行数:57,代码来源:flags.py
示例12: test_default_container_context
def test_default_container_context(self):
default = util.default_container_context()
if selinux.is_selinux_enabled():
# newer policies use container_file_t
self.assertTrue(default in
['system_u:object_r:container_file_t:s0',
'system_u:object_r:svirt_sandbox_file_t:s0'])
else:
self.assertEqual(default, '')
开发者ID:chuanchang,项目名称:atomic,代码行数:9,代码来源:test_util.py
示例13: overwrite_safely
def overwrite_safely(path, content, preserve_mode=True, preserve_context=True):
"""Safely overwrite a file by creating a temporary file in the same
directory, writing it, moving it over the original file, eventually
preserving file mode and SELinux context."""
path = os.path.realpath(path)
dir_ = os.path.dirname(path)
base = os.path.basename(path)
fd = None
f = None
tmpname = None
exists = os.path.exists(path)
if preserve_context and selinux.is_selinux_enabled() <= 0:
preserve_context = False
try:
fd, tmpname = tempfile.mkstemp(prefix=base + os.path.extsep,
dir=dir_)
if exists and preserve_mode:
shutil.copymode(path, tmpname)
if exists and preserve_context:
ret, ctx = selinux.getfilecon(path)
if ret < 0:
raise RuntimeError("getfilecon(%r) failed" % path)
f = os.fdopen(fd, "w")
fd = None
f.write(content)
f.close()
f = None
os.rename(tmpname, path)
if preserve_context:
if exists:
selinux.setfilecon(path, ctx)
else:
selinux.restorecon(path)
finally:
if f:
f.close()
elif fd:
os.close(fd)
if tmpname and os.path.isfile(tmpname):
try:
os.unlink(tmpname)
except:
pass
开发者ID:jfilak,项目名称:python-slip,代码行数:56,代码来源:files.py
示例14: read_cmdline
def read_cmdline(self):
for f in ("selinux", "debug", "leavebootorder", "testing", "extlinux",
"gpt", "dnf"):
self.set_cmdline_bool(f)
if "rpmarch" in self.cmdline:
self.targetarch = self.cmdline.get("rpmarch")
if not selinux.is_selinux_enabled():
self.selinux = 0
开发者ID:fabiand,项目名称:anaconda,代码行数:10,代码来源:flags.py
示例15: _late_setup
def _late_setup(self):
self._selinux_enabled = selinux.is_selinux_enabled()
if not os.path.exists(ohostedcons.FileLocations.VDSMCERT):
self._generateVDSMcerts()
self._copy_vdsm_pki()
if not os.path.exists(
ohostedcons.FileLocations.LIBVIRT_SPICE_SERVER_CERT
):
self._generateSPICEcerts()
self._getSPICEcerts()
开发者ID:aprisun,项目名称:ovirt-hosted-engine-setup,代码行数:10,代码来源:vdsmpki.py
示例16: selinux_role
def selinux_role(self):
"""Setup proper selinux role.
this must be called at beginning of process
to adjust proper roles for selinux.
it will re-execute the process with same arguments.
This has similar effect of:
# chcon -t rpm_exec_t executable.py
We must do this dynamic as this class is to be
used at bootstrap stage, so we cannot put any
persistent selinux policy changes, and have no clue
if filesystem where we put scripts supports extended
attributes, or if we have proper role for chcon.
"""
try:
import selinux
except ImportError:
with self.transaction():
self.install(['libselinux-python'])
if self.buildTransaction():
self.processTransaction()
#
# on fedora-18 for example
# the selinux core is updated
# so we fail resolving symbols
# solution is re-execute the process
# after installation.
#
self._sink.reexec()
os.execv(sys.executable, [sys.executable] + sys.argv)
os._exit(1)
if selinux.is_selinux_enabled():
rc, ctx = selinux.getcon()
if rc != 0:
raise Exception(_('Cannot get selinux context'))
ctx1 = selinux.context_new(ctx)
if not ctx1:
raise Exception(_('Cannot create selinux context'))
if selinux.context_role_get(ctx1) != 'system_r':
if selinux.context_role_set(ctx1, 'system_r') != 0:
raise Exception(
_('Cannot set role within selinux context')
)
if selinux.setexeccon(selinux.context_str(ctx1)) != 0:
raise Exception(
_('Cannot set selinux exec context')
)
self._sink.reexec()
os.execv(sys.executable, [sys.executable] + sys.argv)
os._exit(1)
开发者ID:alonbl,项目名称:otopi,代码行数:55,代码来源:minidnf.py
示例17: main
def main():
module = AnsibleModule(
argument_spec={
'ports': {
'required': True,
},
'proto': {
'required': True,
'choices': ['tcp', 'udp'],
},
'setype': {
'required': True,
},
'state': {
'required': True,
'choices': ['present', 'absent'],
},
'reload': {
'required': False,
'type': 'bool',
'default': 'yes',
},
},
supports_check_mode=True
)
if not HAVE_SELINUX:
module.fail_json(msg="This module requires libselinux-python")
if not HAVE_SEOBJECT:
module.fail_json(msg="This module requires policycoreutils-python")
if not selinux.is_selinux_enabled():
module.fail_json(msg="SELinux is disabled on this host.")
ports = [x.strip() for x in str(module.params['ports']).split(',')]
proto = module.params['proto']
setype = module.params['setype']
state = module.params['state']
do_reload = module.params['reload']
result = {
'ports': ports,
'proto': proto,
'setype': setype,
'state': state,
}
if state == 'present':
result['changed'] = semanage_port_add(module, ports, proto, setype, do_reload)
elif state == 'absent':
result['changed'] = semanage_port_del(module, ports, proto, setype, do_reload)
else:
module.fail_json(msg='Invalid value of argument "state": {0}'.format(state))
module.exit_json(**result)
开发者ID:2ndQuadrant,项目名称:ansible,代码行数:55,代码来源:seport.py
示例18: __copy_from_user
def __copy_from_user(self, user_path, profile_path):
global has_selinux
os.chown(user_path, os.geteuid(), os.getegid())
shutil.move(user_path, profile_path)
if has_selinux:
if selinux.is_selinux_enabled() > 0:
rc, con = selinux.matchpathcon(profile_path, 0)
if rc == 0:
selinux.setfilecon(profile_path, con)
dprint("Moved %s back from %s", user_path, profile_path)
开发者ID:GNOME,项目名称:sabayon,代码行数:11,代码来源:profilesdialog.py
示例19: silent_restorecon
def silent_restorecon(path):
"""Execute selinux restorecon cmd to determined file
Args
path -- full path to file
"""
try:
if selinux.is_selinux_enabled():
selinux.restorecon(path)
except:
__PRINT_AND_LOG("restorecon {p} failed".format(p=path), "error")
开发者ID:aiminickwong,项目名称:ovirt-node-register,代码行数:11,代码来源:system.py
示例20: _silent_restorecon
def _silent_restorecon(path):
"""Execute selinux restorecon cmd to determined file
Args
path -- full path to file
"""
try:
if selinux.is_selinux_enabled():
selinux.restorecon(path)
except:
_LOG.error("restorecon %s failed" % path)
开发者ID:dougsland,项目名称:misc-ovirt,代码行数:12,代码来源:register_node.py
注:本文中的selinux.is_selinux_enabled函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论