本文整理汇总了Python中selinux.is_selinux_enabled函数的典型用法代码示例。如果您正苦于以下问题:Python is_selinux_enabled函数的具体用法?Python is_selinux_enabled怎么用?Python is_selinux_enabled使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_selinux_enabled函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)])
示例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
示例3: selinux_enabled
def selinux_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
示例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")
示例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
示例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)
示例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
示例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
示例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 ""
示例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)
示例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
示例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, '')
示例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
示例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
示例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()