• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python selinux.getfilecon函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: upgradeMountFilesystems

def upgradeMountFilesystems(anaconda):
    # mount everything and turn on swap

    try:
        mountExistingSystem(anaconda, anaconda.upgradeRoot[0], allowDirty = 0)
    except ValueError as e:
        log.error("Error mounting filesystem: %s" % e)
        anaconda.intf.messageWindow(_("Mount failed"),
            _("The following error occurred when mounting the file "
              "systems listed in /etc/fstab.  Please fix this problem "
              "and try to upgrade again.\n%s" % e))
        sys.exit(0)
    except IndexError as e:
        # The upgrade root is search earlier but we give the message here.
        log.debug("No upgrade root was found.")
        if anaconda.ksdata and anaconda.ksdata.upgrade.upgrade:
            anaconda.intf.messageWindow(_("Upgrade root not found"),
                _("The root for the previously installed system was not "
                  "found."), type="custom",
                custom_icon="info",
                custom_buttons=[_("Exit installer")])
            sys.exit(0)
        else:
            rc = anaconda.intf.messageWindow(_("Upgrade root not found"),
                    _("The root for the previously installed system was not "
                      "found.  You can exit installer or backtrack to choose "
                      "installation instead of upgrade."),
                type="custom",
                custom_buttons = [ _("_Back"),
                                   _("_Exit installer") ],
                custom_icon="question")
            if rc == 0:
                return DISPATCH_BACK
            elif rc == 1:
                sys.exit(0)

    checkLinks = ( '/etc', '/var', '/var/lib', '/var/lib/rpm',
                   '/boot', '/tmp', '/var/tmp', '/root',
                   '/bin/sh', '/usr/tmp')
    badLinks = []
    for n in checkLinks:
        if not os.path.islink(anaconda.rootPath + n): continue
        l = os.readlink(anaconda.rootPath + n)
        if l[0] == '/':
            badLinks.append(n)

    if badLinks:
        message = _("The following files are absolute symbolic " 
                    "links, which we do not support during an " 
                    "upgrade. Please change them to relative "
                    "symbolic links and restart the upgrade.\n\n")
        for n in badLinks:
            message = message + '\t' + n + '\n'
        anaconda.intf.messageWindow(_("Absolute Symlinks"), message)
        sys.exit(0)

    # fix for 80446
    badLinks = []
    mustBeLinks = ( '/usr/tmp', )
    for n in mustBeLinks:
        if not os.path.islink(anaconda.rootPath + n):
            badLinks.append(n)

    if badLinks: 
        message = _("The following are directories which should instead "
                    "be symbolic links, which will cause problems with the "
                    "upgrade.  Please return them to their original state "
                    "as symbolic links and restart the upgrade.\n\n")
        for n in badLinks:
            message = message + '\t' + n + '\n'
        anaconda.intf.messageWindow(_("Invalid Directories"), message)
        sys.exit(0)

    anaconda.storage.turnOnSwap(upgrading=True)
    anaconda.storage.mkDevRoot()

    # Move /etc/rpm/platform out of the way.
    if os.path.exists(anaconda.rootPath + "/etc/rpm/platform"):
        shutil.move(anaconda.rootPath + "/etc/rpm/platform",
                    anaconda.rootPath + "/etc/rpm/platform.rpmsave")

    # if they've been booting with selinux disabled, then we should
    # disable it during the install as well (#242510)
    try:
        if os.path.exists(anaconda.rootPath + "/.autorelabel"):
            ctx = selinux.getfilecon(anaconda.rootPath + "/.autorelabel")[1]
            if not ctx or ctx == "unlabeled":
                flags.selinux = False
                log.info("Disabled SELinux for upgrade based on /.autorelabel")
    except Exception, e:
        log.warning("error checking selinux state: %s" %(e,))
开发者ID:BGS,项目名称:rogentos-anaconda,代码行数:91,代码来源:upgrade.py


示例17: default_ro_container_context

def default_ro_container_context():
    if selinux.is_selinux_enabled() != 0:
        return selinux.getfilecon("/usr")[1]
    return ""
开发者ID:14rcole,项目名称:atomic,代码行数:4,代码来源:util.py


示例18: selinux_getfilecon

def selinux_getfilecon(path):
    if have_selinux():
        return selinux.getfilecon(path)[1]
    return None
开发者ID:sandeep-krishnamurthy,项目名称:vm_affinity_management_tool_for_kvm,代码行数:4,代码来源:_util.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python selinux.is_selinux_enabled函数代码示例发布时间:2022-05-27
下一篇:
Python wait.WebDriverWait类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap