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


Python selinux.getfilecon函数代码示例

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


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

示例1: testMountingXFS

    def testMountingXFS(self):
        an_fs = fs.XFS(device=self.loopDevices[0], label="test")
        self.assertIsNone(an_fs.create())

        blivet.flags.installer_mode = False
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertFalse(os.path.exists(lost_and_found))

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:unlabeled_t:s0')

        blivet.flags.installer_mode = True
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertFalse(os.path.exists(lost_and_found))

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:file_t:s0')
开发者ID:wgwoods,项目名称:blivet,代码行数:31,代码来源:selinux_test.py

示例2: get_init_transtype

def get_init_transtype(path):
    entrypoint = selinux.getfilecon(path)[1].split(":")[2]
    try:
        entrypoints = list(filter(lambda x: x['target'] == entrypoint, search([TRANSITION], {'source': "init_t", 'class': 'process'})))
        return entrypoints[0]["transtype"]
    except (TypeError, AttributeError, IndexError):
        pass
    return None
开发者ID:SELinuxProject,项目名称:selinux,代码行数:8,代码来源:__init__.py

示例3: get_file_level

def get_file_level(file_name):
    try:
        context = selinux.getfilecon(file_name)
        context_array = context[1].split(":")
        range = context_array[3]
        range_array = range.split("-")
        level = range_array[0]
    except Exception, ex:
        return "Cancel - getting file level for %s exception: %s" % (file_name, ex)
开发者ID:tedx,项目名称:mls-tools,代码行数:9,代码来源:get_file_level.py

示例4: 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

示例5: get_init_transtype

def get_init_transtype(path):
    entrypoint = selinux.getfilecon(path)[1].split(":")[2]
    try:
        entrypoints = [x for x in search([TRANSITION],{'source':"init_t", 'class':'process'}) if x['target'] == entrypoint]
        if len(entrypoints) == 0:
            return None
        return entrypoints[0]["transtype"]
    except TypeError:
        pass
    return None
开发者ID:rthallisey,项目名称:selinux,代码行数:10,代码来源:__init__.py

示例6: testMountingExt2FS

    def testMountingExt2FS(self):
        _LOOP_DEV0 = self._loopMap[self._LOOP_DEVICES[0]]

        an_fs = fs.Ext2FS(device=_LOOP_DEV0, label="test")
        self.assertIsNone(an_fs.create())

        blivet.flags.installer_mode = False
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:file_t:s0')

        self.assertEqual(lost_and_found_selinux_context[1],
           'system_u:object_r:file_t:s0')

        blivet.flags.installer_mode = True
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        root_selinux_context = selinux.getfilecon(mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(root_selinux_context[1], 'system_u:object_r:file_t:s0')

        self.assertEqual(lost_and_found_selinux_context[1],
           'system_u:object_r:lost_found_t:s0')
开发者ID:Sabayon,项目名称:blivet,代码行数:43,代码来源:selinux_test.py

示例7: get_selinux_context

def get_selinux_context(path):
    """
    When selinux is enabled, return the context of ``path``
    :param path: Full or relative path to a file or directory
    :return: SELinux context as a string
    :raises IOError: As per usual.  Documented here as it's
    a behavior difference from ``set_selinux_context()``.
    """
    # First list item is null-terminated string length
    return selinux.getfilecon(path)[1]
开发者ID:cevich,项目名称:autotest-docker,代码行数:10,代码来源:environment.py

示例8: _gather_data

    def _gather_data(self, path):
        """ Get data on the existing state of <path> -- e.g., whether
        or not it exists, owner, group, permissions, etc. """
        try:
            ondisk = os.stat(path)
        except OSError:
            self.logger.debug("POSIX: %s does not exist" % path)
            return (False, None, None, None, None, None)

        try:
            owner = str(ondisk[stat.ST_UID])
        except OSError:
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current owner of %s: %s" %
                              (path, err))
            owner = None
        except KeyError:
            self.logger.error('POSIX: User resolution failed for %s' % path)
            owner = None

        try:
            group = str(ondisk[stat.ST_GID])
        except (OSError, KeyError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current group of %s: %s" %
                              (path, err))
            group = None
        except KeyError:
            self.logger.error('POSIX: Group resolution failed for %s' % path)
            group = None

        try:
            mode = oct_mode(ondisk[stat.ST_MODE])[-4:]
        except (OSError, KeyError, TypeError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current permissions of "
                              "%s: %s" % (path, err))
            mode = None

        if HAS_SELINUX:
            try:
                secontext = selinux.getfilecon(path)[1].split(":")[2]
            except (OSError, KeyError):
                err = sys.exc_info()[1]
                self.logger.debug("POSIX: Could not get current SELinux "
                                  "context of %s: %s" % (path, err))
                secontext = None
        else:
            secontext = None

        if HAS_ACLS:
            acls = self._list_file_acls(path)
        else:
            acls = None
        return (ondisk, owner, group, mode, secontext, acls)
开发者ID:danfoster,项目名称:bcfg2,代码行数:55,代码来源:base.py

示例9: _gather_data

    def _gather_data(self, path):
        try:
            ondisk = os.stat(path)
        except OSError:
            self.logger.debug("POSIX: %s does not exist" % path)
            return (False, None, None, None, None, None)

        try:
            owner = str(ondisk[stat.ST_UID])
        except OSError:
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current owner of %s: %s" %
                              (path, err))
            owner = None
        except KeyError:
            self.logger.error('POSIX: User resolution failed for %s' % path)
            owner = None

        try:
            group = str(ondisk[stat.ST_GID])
        except (OSError, KeyError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current group of %s: %s" %
                              (path, err))
            group = None
        except KeyError:
            self.logger.error('POSIX: Group resolution failed for %s' % path)
            group = None

        try:
            perms = oct(ondisk[stat.ST_MODE])[-4:]
        except (OSError, KeyError, TypeError):
            err = sys.exc_info()[1]
            self.logger.debug("POSIX: Could not get current permissions of %s: "
                              "%s" % (path, err))
            perms = None

        if has_selinux:
            try:
                secontext = selinux.getfilecon(path)[1].split(":")[2]
            except (OSError, KeyError):
                err = sys.exc_info()[1]
                self.logger.debug("POSIX: Could not get current SELinux "
                                  "context of %s: %s" % (path, err))
                secontext = None
        else:
            secontext = None

        if has_acls:
            acls = self._list_file_acls(path)
        else:
            acls = None
        return (ondisk, owner, group, perms, secontext, acls)
开发者ID:ab,项目名称:bcfg2,代码行数:53,代码来源:base.py

示例10: test_mounting_ext2fs

    def test_mounting_ext2fs(self):
        """ Test that lost+found directory gets assigned correct SELinux
            context if selinux_set_fcon is True, and retains some random old
            context if selinux_set_fcon is False.
        """
        LOST_AND_FOUND_CONTEXT = "system_u:object_r:lost_found_t:s0"
        an_fs = fs.Ext2FS(device=self.loop_devices[0], label="test")

        if not an_fs.formattable or not an_fs.mountable:
            self.skipTest("can not create or mount filesystem %s" % an_fs.name)

        self.assertIsNone(an_fs.create())

        blivet.flags.selinux_reset_fcon = False
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertNotEqual(lost_and_found_selinux_context[1], LOST_AND_FOUND_CONTEXT)

        blivet.flags.selinux_reset_fcon = True
        mountpoint = tempfile.mkdtemp("test.selinux")
        an_fs.mount(mountpoint=mountpoint)

        lost_and_found = os.path.join(mountpoint, "lost+found")
        self.assertTrue(os.path.exists(lost_and_found))

        lost_and_found_selinux_context = selinux.getfilecon(lost_and_found)

        an_fs.unmount()
        os.rmdir(mountpoint)

        self.assertEqual(lost_and_found_selinux_context[1], LOST_AND_FOUND_CONTEXT)
开发者ID:AdamWill,项目名称:blivet,代码行数:40,代码来源:selinux_test.py

示例11: make_polydir_name

def make_polydir_name(dir_name, context):
    (rc, dircon) = selinux.getfilecon(dir_name)
    if rc < 0:
        raise Exception("Error in getting directory context: %s " % (dir_name))
    context_array = dircon.split(":")
    # Only generate polyinstantiated name based on the level not the range
    context_array[3] = get_level(context)
    newcontext = ':'.join(context_array)
    (rc, full_dir) = selinux.selinux_trans_to_raw_context(newcontext)
    if rc < 0:
        raise Exception("Error translating context: %s " % (newcontext))
    m = md5.new()
    m.update(full_dir)
    return dir_name + ".inst/" + m.hexdigest()
开发者ID:tedx,项目名称:mls-tools,代码行数:14,代码来源:polydir.py

示例12: mkdir

def mkdir(target, refdir):
	target = _unicode_encode(target, encoding=_encodings['fs'], errors='strict')
	refdir = _unicode_encode(refdir, encoding=_encodings['fs'], errors='strict')
	(rc, ctx) = selinux.getfilecon(refdir)
	if rc < 0:
		refdir = _unicode_decode(refdir, encoding=_encodings['fs'],
			errors='replace')
		raise OSError(
			_("mkdir: Failed getting context of reference directory \"%s\".") \
			% refdir)

	setfscreate(ctx)
	try:
		os.mkdir(target)
	finally:
		setfscreate()
开发者ID:fastinetserver,项目名称:portage-idfetch,代码行数:16,代码来源:_selinux.py

示例13: analyze

    def analyze(self, avc):
        if not avc.query_environment: return None

        if avc.spath is None: return None
        if avc.spath[0] != '/': return None
        try:
            mcon = selinux.matchpathcon(avc.spath.strip('"'), S_IFREG)[1]
            mcon_type=mcon.split(":")[2]
            gcon = selinux.getfilecon(avc.spath.strip('"'))[1]
            gcon_type = gcon.split(":")[2]
            if mcon_type != gcon_type:
                return self.report((0, mcon_type))
        except OSError:
            pass

        return None
开发者ID:fedora-selinux,项目名称:setroubleshoot,代码行数:16,代码来源:restorecon_source.py

示例14: get_selinux_context

 def get_selinux_context(self, path):
     try:
         (rc, c) = selinux.getfilecon(path)
         return c
     except:
         return None
开发者ID:ebeuerle,项目名称:sos,代码行数:6,代码来源:archive.py

示例15: getcon

 def getcon(self, abspath):
     """ Return context of file, symlink or dir """
     try:
         return selinux.getfilecon(abspath)[1]
     except OSError:
         self._logger.warning('Cannot get selinux context: "%s"', abspath)
开发者ID:vanloswang,项目名称:ovirt-node,代码行数:6,代码来源:security.py


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