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

Python selinux.restorecon函数代码示例

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

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



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

示例1: selinux_restorecon

def selinux_restorecon(path):
    if have_selinux() and hasattr(selinux, "restorecon"):
        try:
            selinux.restorecon(path)
        except Exception, e:
            logging.debug("Restoring context for '%s' failed: %s",
                          path, str(e))
开发者ID:sandeep-krishnamurthy,项目名称:vm_affinity_management_tool_for_kvm,代码行数:7,代码来源:_util.py


示例2: _set_secontext

    def _set_secontext(self, entry, path=None):
        """ set the SELinux context of the file on disk according to the
        config"""
        if not HAS_SELINUX:
            return True

        if path is None:
            path = entry.get("name")
        context = entry.get("secontext")
        if not context:
            # no context listed
            return True

        if context == '__default__':
            try:
                selinux.restorecon(path)
                rv = True
            except OSError:
                err = sys.exc_info()[1]
                self.logger.error("POSIX: Failed to restore SELinux context "
                                  "for %s: %s" % (path, err))
                rv = False
        else:
            try:
                rv = selinux.lsetfilecon(path, context) == 0
            except OSError:
                err = sys.exc_info()[1]
                self.logger.error("POSIX: Failed to restore SELinux context "
                                  "for %s: %s" % (path, err))
                rv = False
        return rv
开发者ID:danfoster,项目名称:bcfg2,代码行数:31,代码来源:base.py


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


示例4: __exit__

    def __exit__(self, exec_ty, exec_val, tb):
        self._context = False
        if exec_ty is None:
            fd, tname = tempfile.mkstemp(dir=os.path.dirname(self._filename))
            try:
                oldlines = self._getOldContent()
                with io.open(fd, 'w', encoding='utf8') as f:
                    if self._section:
                        self._writeSection(f)
                    # if oldlines includes something that we have in
                    #  self._entries we need to write only the new value!
                    for fullline in oldlines:
                        line = fullline.replace(' ', '')
                        key = line.split("=")[0]
                        if key not in self._entries:
                            f.write(fullline)
                        else:
                            f.write(u'## commented out by vdsm\n')
                            f.write(u'# %s\n' % (fullline))
                    if self._entries:
                        self._writeEntries(f)

                os.rename(tname, self._filename)

                if self._oldmod != os.stat(self._filename).st_mode:
                    os.chmod(self._filename, self._oldmod)

                if utils.get_selinux_enforce_mode() > -1:
                    try:
                        selinux.restorecon(self._filename)
                    except OSError:
                        pass  # No default label for file
            finally:
                if os.path.exists(tname):
                    os.remove(tname)
开发者ID:EdDev,项目名称:vdsm,代码行数:35,代码来源:configfile.py


示例5: _set_secontext

    def _set_secontext(self, entry, path=None):  # pylint: disable=R0911
        """ set the SELinux context of the file on disk according to the
        config"""
        if not HAS_SELINUX:
            return True

        if path is None:
            path = entry.get("name")
        context = entry.get("secontext")
        if not context:
            # no context listed
            return True
        secontext = selinux.lgetfilecon(path)[1].split(":")[2]
        if secontext in Bcfg2.Options.setup.secontext_ignore:
            return True
        try:
            if context == '__default__':
                selinux.restorecon(path)
                return True
            else:
                return selinux.lsetfilecon(path, context) == 0
        except OSError:
            err = sys.exc_info()[1]
            if err.errno == errno.EOPNOTSUPP:
                # Operation not supported
                if context != '__default__':
                    self.logger.debug("POSIX: Failed to set SELinux context "
                                      "for %s: %s" % (path, err))
                    return False
                return True
            err = sys.exc_info()[1]
            self.logger.error("POSIX: Failed to set or restore SELinux "
                              "context for %s: %s" % (path, err))
            return False
开发者ID:fennm,项目名称:bcfg2,代码行数:34,代码来源:base.py


示例6: __exit__

    def __exit__(self, exec_ty, exec_val, tb):

        self._context = False
        if exec_ty is None:
            fd, tname = tempfile.mkstemp(dir=os.path.dirname(self._filename))
            try:
                oldlines, oldentries = self._getOldContent()
                with os.fdopen(fd, 'w', ) as f:
                    if self._section:
                        self._writeSection(f)
                    f.writelines(oldlines)
                    if self._entries:
                        self._writeEntries(f, oldentries)

                if utils.isOvirtNode():
                    NodeCfg().unpersist(self._filename)
                os.rename(tname, self._filename)
                if utils.isOvirtNode():
                    NodeCfg().persist(self._filename)

                if self._oldmod != os.stat(self._filename).st_mode:
                    os.chmod(self._filename, self._oldmod)

                if selinux.is_selinux_enabled:
                    try:
                        selinux.restorecon(self._filename)
                    except OSError:
                        pass  # No default label for file
            finally:
                if os.path.exists(tname):
                    os.remove(tname)
开发者ID:futurice,项目名称:vdsm,代码行数:31,代码来源:configfile.py


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


示例8: writeConfFile

 def writeConfFile(self, fileName, configuration):
     """Backs up the previous contents of the file referenced by fileName
     writes the new configuration and sets the specified access mode."""
     self._backup(fileName)
     open(fileName, "w").write(configuration)
     os.chmod(fileName, 0664)
     try:
         selinux.restorecon(fileName)
     except:
         logging.debug("ignoring restorecon error in case " "SElinux is disabled", exc_info=True)
开发者ID:edwardbadboy,项目名称:vdsm-ubuntu,代码行数:10,代码来源:ifcfg.py


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


示例10: _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


示例11: _silent_restorecon

    def _silent_restorecon(self, path):
        """
        Execute selinux restorecon cmd to determined file

        Args
        path -- full path to file
        """

        try:
            selinux.restorecon(path)
        except:
            self.logger.error("restorecon %s failed" % path, exc_info=True)
开发者ID:nirs,项目名称:vdsm,代码行数:12,代码来源:register.py


示例12: copyfile

def copyfile(srcpath, dstpath, copy_mode_from_dst=True, run_restorecon=True):
    """Copy srcpath to dstpath.

    Abort operation if e.g. not enough space is available.  Attempt to
    atomically replace dstpath if it exists."""

    if issamefile(srcpath, dstpath, catch_stat_exceptions=OSError):
        return

    dstpath = os.path.abspath(dstpath)
    dstdname = os.path.dirname(dstpath)
    dstbname = os.path.basename(dstpath)

    srcfile = open(srcpath, "rb")
    dsttmpfile = tempfile.NamedTemporaryFile(
        prefix=dstbname + os.path.extsep, dir=dstdname, delete=False)

    mode_copied = False

    if copy_mode_from_dst:

        # attempt to copy mode from destination file (if it exists,
        # otherwise fall back to copying it from the source file below)

        try:
            shutil.copymode(dstpath, dsttmpfile.name)
            mode_copied = True
        except (shutil.Error, OSError):
            pass

    if not mode_copied:
        shutil.copymode(srcpath, dsttmpfile.name)

    data = None

    while data != "":
        data = srcfile.read(BLOCKSIZE)
        try:
            dsttmpfile.write(data)
        except:
            srcfile.close()
            dsttmpfile.close()
            os.unlink(dsttmpfile.name)
            raise

    srcfile.close()
    dsttmpfile.close()

    os.rename(dsttmpfile.name, dstpath)

    if run_restorecon and selinux.is_selinux_enabled() > 0:
        selinux.restorecon(dstpath)
开发者ID:jfilak,项目名称:python-slip,代码行数:52,代码来源:files.py


示例13: writeConfFile

 def writeConfFile(self, fileName, configuration):
     '''Backs up the previous contents of the file referenced by fileName
     writes the new configuration and sets the specified access mode.'''
     self._backup(fileName)
     logging.debug('Writing to file %s configuration:\n%s' % (fileName,
                   configuration))
     with open(fileName, 'w') as confFile:
         confFile.write(configuration)
     os.chmod(fileName, 0o664)
     try:
         selinux.restorecon(fileName)
     except:
         logging.debug('ignoring restorecon error in case '
                       'SElinux is disabled', exc_info=True)
开发者ID:therealmik,项目名称:vdsm,代码行数:14,代码来源:ifcfg.py


示例14: _install_file

def _install_file(src, dst):
    _log("Installing %s at %s", src, dst)
    tmpfile = _LVMLOCAL_CUR + ".tmp"
    shutil.copyfile(_LVMLOCAL_VDSM, tmpfile)
    try:
        selinux.restorecon(tmpfile)
        os.chmod(tmpfile, 0o644)
        os.rename(tmpfile, _LVMLOCAL_CUR)
    except:
        try:
            os.unlink(tmpfile)
        except Exception:
            _log("ERROR: cannot remove temporary file: %s", tmpfile)
        raise
开发者ID:nirs,项目名称:vdsm,代码行数:14,代码来源:lvm.py


示例15: _getSSH

    def _getSSH(self):
        pkihelper = pkissh.PKIHelper()
        authorized_keys_line = pkihelper.getSSHkey(
            fqdn=self.environment[
                ohostedcons.NetworkEnv.OVIRT_HOSTED_ENGINE_FQDN
            ],
            ca_certs=self.environment[
                ohostedcons.EngineEnv.TEMPORARY_CERT_FILE
            ],
        )

        authorized_keys_file = os.path.join(
            os.path.expanduser('~root'),
            '.ssh',
            'authorized_keys'
        )

        content = pkihelper.mergeAuthKeysFile(
            authorized_keys_file, authorized_keys_line
        )
        with transaction.Transaction() as localtransaction:
            localtransaction.append(
                filetransaction.FileTransaction(
                    name=authorized_keys_file,
                    content=content,
                    mode=0o600,
                    owner='root',
                    enforcePermissions=True,
                    modifiedList=self.environment[
                        otopicons.CoreEnv.MODIFIED_FILES
                    ],
                )
            )

        if self._selinux_enabled:
            path = os.path.join(
                os.path.expanduser('~root'),
                '.ssh'
            )
            try:
                selinux.restorecon(path, recursive=True)
            except OSError as ex:
                self.logger.error(
                    _(
                        'Failed to refresh SELINUX context for {path}: {ex}'
                    ).format(
                        path=path,
                        ex=ex.message,
                    )
                )
开发者ID:tiraboschi,项目名称:ovirt-hosted-engine-setup,代码行数:50,代码来源:add_host.py


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


示例17: reset

 def reset(self):
     root=self.graphdir
     try:
         self.d.info()
         raise ValueError("Docker daemon must be stopped before resetting storage")
     except (NoDockerDaemon, requests.exceptions.ConnectionError):
         pass
     util.check_call(["docker-storage-setup", "--reset"], stdout=DEVNULL)
     util.call(["umount", root + "/devicemapper"], stderr=DEVNULL)
     util.call(["umount", root + "/overlay"], stderr=DEVNULL)
     util.call(["umount", root + "/overlay2"], stderr=DEVNULL)
     shutil.rmtree(root)
     os.mkdir(root)
     try:
         selinux.restorecon(root.encode("utf-8"))
     except (TypeError, OSError):
         selinux.restorecon(root)
开发者ID:jlebon,项目名称:atomic,代码行数:17,代码来源:storage.py


示例18: _install_file

def _install_file(src, dst):
    _log("Installing %s at %s", src, dst)
    tmpfile = _LVMLOCAL_CUR + ".tmp"
    shutil.copyfile(_LVMLOCAL_VDSM, tmpfile)
    try:
        # TODO: remove when we require selinux version that does not explode
        # when selinux is disabled.
        if selinux.is_selinux_enabled():
            selinux.restorecon(tmpfile)
        os.chmod(tmpfile, 0o644)
        os.rename(tmpfile, _LVMLOCAL_CUR)
    except:
        try:
            os.unlink(tmpfile)
        except Exception:
            _log("ERROR: cannot remove temporary file: %s", tmpfile)
        raise
开发者ID:EdDev,项目名称:vdsm,代码行数:17,代码来源:lvm.py


示例19: writeConfFile

    def writeConfFile(self, fileName, configuration):
        """Backs up the previous contents of the file referenced by fileName
        writes the new configuration and sets the specified access mode."""
        self._backup(fileName)
        configuration = self.CONFFILE_HEADER + "\n" + configuration

        logging.debug("Writing to file %s configuration:\n%s", fileName, configuration)
        with open(fileName, "w") as confFile:
            confFile.write(configuration)
        os.chmod(fileName, 0o664)

        try:
            # filname can be of 'unicode' type. restorecon calls into a C API
            # that needs a char *. Thus, it is necessary to encode unicode to
            # a utf-8 string.
            selinux.restorecon(fileName.encode("utf-8"))
        except:
            logging.debug("ignoring restorecon error in case " "SElinux is disabled", exc_info=True)
开发者ID:nirs,项目名称:vdsm,代码行数:18,代码来源:ifcfg.py


示例20: configure

def configure():
    """
    Set up the multipath daemon configuration to the known and
    supported state. The original configuration, if any, is saved
    """

    if os.path.exists(_CONF_FILE):
        backup = _CONF_FILE + '.' + time.strftime("%Y%m%d%H%M")
        shutil.copyfile(_CONF_FILE, backup)
        sys.stdout.write("Backup previous multipath.conf to %r\n" % backup)
        utils.persist(backup)

    with tempfile.NamedTemporaryFile(
            mode="wb",
            prefix=os.path.basename(_CONF_FILE) + ".tmp",
            dir=os.path.dirname(_CONF_FILE),
            delete=False) as f:
        try:
            f.write(_CONF_DATA)
            f.flush()
            if selinux.is_selinux_enabled():
                selinux.restorecon(f.name)
            os.chmod(f.name, 0o644)
            # On ovirt node multipath.conf is a bind mount and rename will fail
            # if we do not unpersist first, making this non-atomic.
            utils.unpersist(_CONF_FILE)
            os.rename(f.name, _CONF_FILE)
        except:
            os.unlink(f.name)
            raise

    utils.persist(_CONF_FILE)

    # Flush all unused multipath device maps
    utils.execCmd([constants.EXT_MULTIPATH, "-F"])

    try:
        service.service_reload("multipathd")
    except service.ServiceOperationError:
        status = service.service_status("multipathd", False)
        if status == 0:
            raise
开发者ID:fancyKai,项目名称:vdsm,代码行数:42,代码来源:multipath.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python common.Method类代码示例发布时间:2022-05-27
下一篇:
Python selinux.is_selinux_enabled函数代码示例发布时间: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