Python os.fchdir() Examples

The following are 10 code examples of os.fchdir(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: drecurse.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def _recursive_dirlist(prepend, xdev, bup_dir=None, excluded_paths=None):
    for (name,pst) in _dirlist():
        if name.endswith('/'):
            if xdev != None and pst.st_dev != xdev:
                debug1('Skipping %r: different filesystem.\n' % (prepend+name))
                continue
            if bup_dir != None:
                if os.path.normpath(prepend+name) == bup_dir:
                    debug1('Skipping BUP_DIR.\n')
                    continue
            if excluded_paths:
                if os.path.normpath(prepend+name) in excluded_paths:
                    debug1('Skipping %r: excluded.\n' % (prepend+name))
                    continue
            try:
                OsFile(name).fchdir()
            except OSError, e:
                add_error('%s: %s' % (prepend, e))
            else:
                for i in _recursive_dirlist(prepend=prepend+name, xdev=xdev,
                                            bup_dir=bup_dir,
                                            excluded_paths=excluded_paths):
                    yield i
                os.chdir('..')
        yield (prepend + name, pst) 
Example #2
Source File: files.py    From conary with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: worker.py    From container-breakouts with Apache License 2.0 5 votes vote down vote up
def worker():
  serv = Client('\0singe', authkey=b'peekaboo')
  serv.send(os.getpid())
  fd = recv_handle(serv)
  print('WORKER: GOT FD', fd)
  os.fchdir(fd)
  os.execl("/bin/dash", "/bin/dash", "-i") 
Example #4
Source File: drecurse.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def fchdir(self):
        os.fchdir(self.fd) 
Example #5
Source File: drecurse.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def recursive_dirlist(paths, xdev, bup_dir=None, excluded_paths=None):
    startdir = OsFile('.')
    try:
        assert(type(paths) != type(''))
        for path in paths:
            try:
                pst = xstat.lstat(path)
                if stat.S_ISLNK(pst.st_mode):
                    yield (path, pst)
                    continue
            except OSError, e:
                add_error('recursive_dirlist: %s' % e)
                continue
            try:
                pfile = OsFile(path)
            except OSError, e:
                add_error(e)
                continue
            pst = pfile.stat()
            if xdev:
                xdev = pst.st_dev
            else:
                xdev = None
            if stat.S_ISDIR(pst.st_mode):
                pfile.fchdir()
                prepend = os.path.join(path, '')
                for i in _recursive_dirlist(prepend=prepend, xdev=xdev,
                                            bup_dir=bup_dir,
                                            excluded_paths=excluded_paths):
                    yield i
                startdir.fchdir()
            else:
                prepend = path
            yield (prepend,pst) 
Example #6
Source File: ratarmount.py    From ratarmount with MIT License 5 votes vote down vote up
def init( self, connection ):
        os.fchdir( self.mountPointFd )
        for i in range( len( self.mountSources ) ):
            if self.mountSources[i] == self.mountPoint:
                self.mountSources[i] = '.' 
Example #7
Source File: templateUtils.py    From Coffer with MIT License 5 votes vote down vote up
def executeCommand(command):
    cwd = os.getcwd()
    rr = os.open("/", os.O_RDONLY)
    os.chroot(getRootDir.getEnvsDir() + getEnvName())
    os.chdir("/")
    os.system(command)
    os.fchdir(rr)
    os.chroot(".")
    os.chdir(cwd) 
Example #8
Source File: files.py    From conary with Apache License 2.0 5 votes vote down vote up
def lookupName(self, root, name):
        theId = self.nameCache.get(name, None)
        if theId is not None:
            return theId

        # if not root, cannot chroot and so fall back to system ids
        getChrootIds = root and root != '/' and not os.getuid()

        if getChrootIds:
            if root[0] != '/':
                root = os.sep.join((os.getcwd(), root))
            curDir = os.open(".", os.O_RDONLY)
            # chdir to the current root to allow us to chroot
            # back out again
            os.chdir('/')
            os.chroot(root)

        if name and name[0] == '+':
            # An id mapped as a string
            try:
                theId = int(name)
            except ValueError:
                log.warning('%s %s does not exist - using root', self.name,
                            name)
        else:
            try:
                theId = self.nameLookupFn(name)[2]
            except KeyError:
                log.warning('%s %s does not exist - using root', self.name, name)
                theId = 0

        if getChrootIds:
            os.chroot(".")
            os.fchdir(curDir)
            os.close(curDir)

        self.nameCache[name] = theId
        self.idCache[theId] = name
        return theId 
Example #9
Source File: release_tool.py    From integration with Apache License 2.0 4 votes vote down vote up
def execute_git(state, repo_git, args, capture=False, capture_stderr=False):
    """Executes a Git command in the given repository, with args being a list
    of arguments (not including git itself). capture and capture_stderr
    arguments causes it to return stdout or stdout+stderr as a string.

    state can be None, but if so, then repo_git needs to be an absolute path.

    The function automatically takes into account Git commands with side effects
    and applies push simulation and dry run if those are enabled."""

    is_push = args[0] == "push"
    is_change = (
        is_push
        or (args[0] == "tag" and len(args) > 1)
        or (args[0] == "branch" and len(args) > 1)
        or (args[0] == "config" and args[1] != "-l")
        or (args[0] == "checkout")
        or (args[0] == "commit")
        or (args[0] == "fetch")
        or (args[0] == "init")
        or (args[0] == "reset")
    )

    if os.path.isabs(repo_git):
        git_dir = repo_git
    else:
        git_dir = os.path.join(state["repo_dir"], repo_git)

    if (not PUSH and is_push) or (DRY_RUN and is_change):
        print("Would have executed: cd %s && git %s" % (git_dir, " ".join(args)))
        return None

    fd = os.open(".", flags=os.O_RDONLY)
    os.chdir(git_dir)
    if capture_stderr:
        stderr = subprocess.STDOUT
    else:
        stderr = None

    try:
        if capture:
            output = (
                subprocess.check_output(["git"] + args, stderr=stderr).decode().strip()
            )
        else:
            output = None
            subprocess.check_call(["git"] + args, stderr=stderr)
    finally:
        os.fchdir(fd)
        os.close(fd)

    return output 
Example #10
Source File: rpmcapsule.py    From conary with Apache License 2.0 4 votes vote down vote up
def flushRpmLog(self):
        s = os.read(self.logFd, 50000)
        data = ''
        while s:
            data += s
            s = os.read(self.logFd, 50000)

        lines = data.split('\n')
        if not lines:
            return

        # We're in RPM's chroot jail. We'll break out of it so that
        # the callbacks work as expected, but we need to restore both
        # the chroot and the cwd.
        thisRoot = os.open("/", os.O_RDONLY)
        thisDir = os.open(".", os.O_RDONLY)
        concats = []

        try:
            os.fchdir(self.rootFd)
            os.chroot(".")

            for line in lines:
                line.strip()
                if not line:
                    continue

                # this passwd/group stuff is for CNY-3428. Basically group
                # info packages can create users before Red Hat's setup
                # package is installed. this fixes things up.
                if '/etc/passwd.rpmnew' in line:
                    concats.append( ('/etc/passwd', '/etc/passwd.rpmnew') )
                elif '/etc/group.rpmnew' in line:
                    concats.append( ('/etc/group', '/etc/group.rpmnew') )
                elif line.startswith('error:'):
                    line = line[6:].strip()
                    self.callback.error(line)
                elif line.startswith('warning:'):
                    line = line[8:].strip()
                    self.callback.warning(line)
                else:
                    self.callback.warning(line)
        finally:
            os.fchdir(thisRoot)
            os.close(thisRoot)
            os.chroot(".")
            os.fchdir(thisDir)
            os.close(thisDir)

        for (keepPath, fromPath) in concats:
            finalLines = open(fromPath).readlines() + open(keepPath).readlines()
            finalLines = [ (x.split(':')[0], x) for x in finalLines ]
            seen = set()
            f = open(keepPath, "w")
            for (name, line) in finalLines:
                if name not in seen:
                    seen.add(name)
                    f.write(line)

            f.close()
            os.unlink(fromPath)