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


Python selinux.restorecon函数代码示例

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


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


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