當前位置: 首頁>>代碼示例>>Python>>正文


Python os.chroot方法代碼示例

本文整理匯總了Python中os.chroot方法的典型用法代碼示例。如果您正苦於以下問題:Python os.chroot方法的具體用法?Python os.chroot怎麽用?Python os.chroot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在os的用法示例。


在下文中一共展示了os.chroot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _setup_root_filesystem

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def _setup_root_filesystem(self, root_dir):
        """Setup the filesystem layout in the given root directory.
        Create a copy of the existing proc- and dev-mountpoints in the specified root
        directory. Afterwards we chroot into it.

        @param root_dir:
            The path of the root directory that is used to execute the process.
        """
        root_dir = root_dir.encode()

        # Create an empty proc folder into the root dir. The grandchild still needs a
        # view of the old /proc, therefore we do not mount a fresh /proc here.
        proc_base = os.path.join(root_dir, b"proc")
        os.makedirs(proc_base, exist_ok=True)

        dev_base = os.path.join(root_dir, b"dev")
        os.makedirs(dev_base, exist_ok=True)

        # Create a copy of the host's dev- and proc-mountpoints.
        # They are marked as private in order to not being changed
        # by existing mounts during run execution.
        container.make_bind_mount(b"/dev/", dev_base, recursive=True, private=True)
        container.make_bind_mount(b"/proc/", proc_base, recursive=True, private=True)

        os.chroot(root_dir) 
開發者ID:sosy-lab,項目名稱:benchexec,代碼行數:27,代碼來源:containerexecutor.py

示例2: change_root_directory

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def change_root_directory(directory):
    """ Change the root directory of this process.

        Sets the current working directory, then the process root
        directory, to the specified `directory`. Requires appropriate
        OS privileges for this process.

        """
    try:
        os.chdir(directory)
        os.chroot(directory)
    except Exception, exc:
        error = DaemonOSEnvironmentError(
            "Unable to change root directory (%(exc)s)"
            % vars())
        raise error 
開發者ID:blackye,項目名稱:luscan-devel,代碼行數:18,代碼來源:daemon.py

示例3: chroot

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def chroot(root):
    """
    Chroot into a separate directory to isolate ourself for increased security.
    """
    # preload for socket.gethostbyaddr()
    import encodings.idna

    try:
        os.chroot(root)
        os.chdir('/')
        logger.info('chrooted successfully to {}'.format(root))
    except Exception as e:
        logger.error('could not chroot to {}: {}'.format(root, e))
        return False

    return True 
開發者ID:christgau,項目名稱:wsdd,代碼行數:18,代碼來源:wsdd.py

示例4: lookupId

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def lookupId(self, root, theId):
        theName = self.idCache.get(theId, None)
        if theName is not None:
            return theName

        if root and root != '/':
            curDir = os.open(".", os.O_RDONLY)
            os.chdir("/")
            os.chroot(root)

        name = self.idLookupFn(theId)[0]
        if root and root != '/':
            os.chroot(".")
            os.fchdir(curDir)
            os.close(curDir)

        self.nameCache[name] = theId
        self.idCache[theId] = name
        return name 
開發者ID:sassoftware,項目名稱:conary,代碼行數:21,代碼來源:files.py

示例5: testTagHandlerDoesNotExist

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def testTagHandlerDoesNotExist(self):
        myRecipe = recipes.multiTagRecipe0
        myRecipe += '        r.ComponentSpec(":tag", "%(taghandlerdir)s/")\n'
        multitag = self.build(myRecipe, "MultiTag", returnTrove='multitag')
        self.updatePkg('multitag:runtime')
        fooFile = rephelp.RegularFile(
                                contents = 'foo\n',
                                perms = 0644, tags = [ 'foo' ] )
        self.addComponent('foo:runtime', [('/bam', fooFile)])
        oldFuncs = (os.getuid, os.lchown, os.chroot)

        self.mock(os, "getuid", lambda : 0)
        self.mock(os, "lchown", lambda x, y, z : None)
        self.mock(os, "chroot", lambda x :None)
        # this fixes a race between new tag handler process exiting and
        # writing files into the pipe for that tag handler; we let the
        # write finish before the handler process terminates
        origExec = os.execve
        self.mock(os, "execve", lambda *args : (time.sleep(0.1),
                                                origExec(*args)))

        rc, txt = self.captureOutput(self.updatePkg, 'foo:runtime',
                                     _removeBokenPipeErrors=True)

        self.assertEquals(txt.lstrip(), '[foo] [Errno 2] No such file or directory\nerror: /usr/libexec/conary/tags/foo failed\n') 
開發者ID:sassoftware,項目名稱:conary,代碼行數:27,代碼來源:tagtest.py

示例6: chroot

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def chroot(self):
			os.chroot(self) 
開發者ID:OpenMTC,項目名稱:OpenMTC,代碼行數:4,代碼來源:__init__.py

示例7: chroot

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def chroot(self):
            os.chroot(self) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:4,代碼來源:_path.py

示例8: setUp

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def setUp(self):
        self.root = self.unset
        self.cwd = self.unset
        self.mask = self.unset
        self.daemon = False
        self.pid = os.getpid()
        self.patch(os, 'chroot', lambda path: setattr(self, 'root', path))
        self.patch(os, 'chdir', lambda path: setattr(self, 'cwd', path))
        self.patch(os, 'umask', lambda mask: setattr(self, 'mask', mask))
        self.runner = UnixApplicationRunner(twistd.ServerOptions())
        self.runner.daemonize = self.daemonize 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:13,代碼來源:test_twistd.py

示例9: test_chroot

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def test_chroot(self):
        """
        L{UnixApplicationRunner.setupEnvironment} changes the root of the
        filesystem if passed a non-L{None} value for the C{chroot} parameter.
        """
        self.runner.setupEnvironment("/foo/bar", ".", True, None, None)
        self.assertEqual(self.root, "/foo/bar") 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:9,代碼來源:test_twistd.py

示例10: test_noChroot

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def test_noChroot(self):
        """
        L{UnixApplicationRunner.setupEnvironment} does not change the root of
        the filesystem if passed L{None} for the C{chroot} parameter.
        """
        self.runner.setupEnvironment(None, ".", True, None, None)
        self.assertIs(self.root, self.unset) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:9,代碼來源:test_twistd.py

示例11: setupEnvironment

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def setupEnvironment(self, chroot, rundir, nodaemon, umask, pidfile):
        """
        Set the filesystem root, the working directory, and daemonize.

        @type chroot: C{str} or L{None}
        @param chroot: If not None, a path to use as the filesystem root (using
            L{os.chroot}).

        @type rundir: C{str}
        @param rundir: The path to set as the working directory.

        @type nodaemon: C{bool}
        @param nodaemon: A flag which, if set, indicates that daemonization
            should not be done.

        @type umask: C{int} or L{None}
        @param umask: The value to which to change the process umask.

        @type pidfile: C{str} or L{None}
        @param pidfile: If not L{None}, the path to a file into which to put
            the PID of this process.
        """
        daemon = not nodaemon

        if chroot is not None:
            os.chroot(chroot)
            if rundir == '.':
                rundir = '/'
        os.chdir(rundir)
        if daemon and umask is None:
            umask = 0o077
        if umask is not None:
            os.umask(umask)
        if daemon:
            from twisted.internet import reactor
            self.config["statusPipe"] = self.daemonize(reactor)
        if pidfile:
            with open(pidfile, 'wb') as f:
                f.write(intToBytes(os.getpid())) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:41,代碼來源:_twistd_unix.py

示例12: contain

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def contain(command, image_name, image_dir, container_id, container_dir):
    try:
        linux.unshare(linux.CLONE_NEWNS)  # create a new mount namespace
    except RuntimeError as e:
        if getattr(e, 'args', '') == (1, 'Operation not permitted'):
            print('Error: Use of CLONE_NEWNS with unshare(2) requires the '
                  'CAP_SYS_ADMIN capability (i.e. you probably want to retry '
                  'this with sudo)')
        raise e

    # TODO: we added MS_REC here. wanna guess why?
    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    # Create mounts (/proc, /sys, /dev) under new_root
    linux.mount('proc', os.path.join(new_root, 'proc'), 'proc', 0, '')
    linux.mount('sysfs', os.path.join(new_root, 'sys'), 'sysfs', 0, '')
    linux.mount('tmpfs', os.path.join(new_root, 'dev'), 'tmpfs',
                linux.MS_NOSUID | linux.MS_STRICTATIME, 'mode=755')

    # Add some basic devices
    devpts_path = os.path.join(new_root, 'dev', 'pts')
    if not os.path.exists(devpts_path):
        os.makedirs(devpts_path)
        linux.mount('devpts', devpts_path, 'devpts', 0, '')

    makedev(os.path.join(new_root, 'dev'))

    os.chroot(new_root)  # TODO: replace with pivot_root

    os.chdir('/')

    # TODO: umount2 old root (HINT: see MNT_DETACH in man 2 umount)

    os.execvp(command[0], command) 
開發者ID:Fewbytes,項目名稱:rubber-docker,代碼行數:40,代碼來源:rd.py

示例13: contain

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def contain(command, image_name, image_dir, container_id, container_dir):
    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    # TODO: time to say goodbye to the old mount namespace,
    #       see "man 2 unshare" to get some help
    #   HINT 1: there is no os.unshare(), time to use the linux module we made
    #           just for you!
    #   HINT 2: the linux module includes both functions and constants!
    #           e.g. linux.CLONE_NEWNS

    # TODO: remember shared subtrees?
    # (https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt)
    # Make / a private mount to avoid littering our host mount table.

    # Create mounts (/proc, /sys, /dev) under new_root
    linux.mount('proc', os.path.join(new_root, 'proc'), 'proc', 0, '')
    linux.mount('sysfs', os.path.join(new_root, 'sys'), 'sysfs', 0, '')
    linux.mount('tmpfs', os.path.join(new_root, 'dev'), 'tmpfs',
                linux.MS_NOSUID | linux.MS_STRICTATIME, 'mode=755')
    # Add some basic devices
    devpts_path = os.path.join(new_root, 'dev', 'pts')
    if not os.path.exists(devpts_path):
        os.makedirs(devpts_path)
        linux.mount('devpts', devpts_path, 'devpts', 0, '')
    for i, dev in enumerate(['stdin', 'stdout', 'stderr']):
        os.symlink('/proc/self/fd/%d' % i, os.path.join(new_root, 'dev', dev))

    # TODO: add more devices (e.g. null, zero, random, urandom) using os.mknod.

    os.chroot(new_root)

    os.chdir('/')

    os.execvp(command[0], command) 
開發者ID:Fewbytes,項目名稱:rubber-docker,代碼行數:38,代碼來源:rd.py

示例14: orphansKill

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def orphansKill(rootToKill, manual_forced=False):
    """
    Kill off anything that is still chrooted.

    When USE_NSPAWN==False, this method manually detects the running processes
    in chroot by reading the /proc file-system.  When USE_NSPAWN==True, it just
    relies on '/bin/machinectl terminate' call.

    When manual_forced==True, the manual kill based on /proc is enforced.
    """
    getLog().debug("kill orphans")
    if USE_NSPAWN is False or manual_forced:
        path_cache = {}
        for killsig in [signal.SIGTERM, signal.SIGKILL]:
            for fn in [d for d in os.listdir("/proc") if d.isdigit()]:
                try:
                    root = os.readlink("/proc/%s/root" % fn)
                    if compare_two_paths_cached(root, rootToKill, path_cache):
                        getLog().warning("Process ID %s still running in chroot. Killing with %s...", fn, killsig)
                        pid = int(fn, 10)
                        os.kill(pid, killsig)
                        os.waitpid(pid, 0)
                except OSError:
                    pass
    else:
        m_uuid = get_machinectl_uuid(rootToKill)
        if m_uuid:
            getLog().warning("Machine %s still running. Killing...", m_uuid)
            os.system("/bin/machinectl terminate %s" % m_uuid) 
開發者ID:rpm-software-management,項目名稱:mock,代碼行數:31,代碼來源:util.py

示例15: condChroot

# 需要導入模塊: import os [as 別名]
# 或者: from os import chroot [as 別名]
def condChroot(chrootPath):
    if chrootPath is not None:
        saved = {"ruid": os.getuid(), "euid": os.geteuid()}
        setresuid(0, 0, 0)
        os.chdir(chrootPath)
        os.chroot(chrootPath)
        setresuid(saved['ruid'], saved['euid']) 
開發者ID:rpm-software-management,項目名稱:mock,代碼行數:9,代碼來源:util.py


注:本文中的os.chroot方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。