Example #1
0
    def add_file(self, fs_dir, f):
        fn = os.path.join(fs_dir, f.name)

        if f.ftype == fs.REGULAR:
            dbf = self.body_db.file_db.files[f.file_id]
            self.body_db.file_store.extract_file(fn, dbf.offset, dbf.zlength)

        elif f.ftype == fs.SYMLINK:
            os.symlink(f.target, fn)

        elif f.ftype == fs.SOCKET:
            s = socket.socket(socket.AF_UNIX)
            s.bind(fn)
            s.close()

        elif f.ftype == fs.FIFO:
            os.mkfifo(fn, f.mode)

        else:
            mode = f.mode | stat.S_IFBLK if f.ftype == fs.BLOCKDEV else stat.S_IFCHR
            device = os.makedev(f.major, f.minor)
            os.mknod(fn, mode, device)

        try:
            os.lchown(fn, f.uid, f.gid)
        except:
            pass

        if not f.ftype == fs.SYMLINK:
            os.chmod(fn, f.mode)

        cwrap.set_nsec_mtime(fn, f.mtime_ns)
Example #2
0
def chpath_inplace_symlink(filename, st, old, new):
	target = os.readlink(filename)
	if target.startswith(old):
		new_target = new + target[len(old):]
		os.unlink(filename)
		os.symlink(new_target, filename)
		os.lchown(filename, st.st_uid, st.st_gid)
Example #3
0
def lchown(space, path, uid, gid):
    """Change the owner and group id of path to the numeric uid and gid.
This function will not follow symbolic links."""
    try:
        os.lchown(path, uid, gid)
    except OSError as e:
        raise wrap_oserror(space, e, path)
Example #4
0
    def setPermissions(self, root, target, journal=None, nameLookup=True):
        # do the chmod after the chown because some versions of Linux
        # remove setuid/gid flags when changing ownership to root
        if journal:
            journal.lchown(root, target, self.inode.owner(),
                           self.inode.group())
            self.chmod(target)
            return

        global userCache, groupCache
        uid = gid = 0
        owner = self.inode.owner()
        group = self.inode.group()
        # not all file types have owners
        if owner and nameLookup:
            uid = userCache.lookupName(root, owner)
        if group and nameLookup:
            gid = groupCache.lookupName(root, group)
        ruid = os.getuid()
        mask = 0

        if ruid == 0:
            os.lchown(target, uid, gid)
        else:
            # do not ever make a file setuid or setgid the wrong user
            rgid = os.getgid()
            if uid != ruid:
                mask |= 04000
            if gid != rgid:
                mask |= 02000
        self.chmod(target, mask)
Example #5
0
    def copy(path):
        global copied_files

        source = os.path.join(source_dir, path)
        target = os.path.join(target_dir, path)

        if os.path.isdir(source):
            os.mkdir(target, 0755)
            os.chown(target, installation.system.uid, installation.system.gid)
            created_dir.append(target)
            return True
        else:
            copyfile(source, target)
            created_file.append(target)
            if not os.path.islink(target):
                if path.startswith("hooks/"):
                    mode = 0755
                else:
                    mode = 0644
                os.chmod(target, mode)
            os.lchown(target, installation.system.uid, installation.system.gid)
            copied_files += 1
            if not compile_file(path):
                compilation_failed.append(path)
            return False
Example #6
0
    def __restore_attributes(self, tar_info, path):
        """Restores all attributes of a restored file."""

        if os.geteuid() == 0:
            try:
                try:
                    uid = utils.getpwnam(tar_info.uname)[2]
                except KeyError:
                    uid = tar_info.uid

                try:
                    gid = utils.getgrnam(tar_info.gname)[2]
                except KeyError:
                    gid = tar_info.gid

                os.lchown(path, uid, gid)
            except Exception as e:
                if not psys.is_errno(e, errno.ENOENT):
                    LOG.error("Failed to set owner of '%s': %s.", path, psys.e(e))
                    self.__ok = False

        if not tar_info.issym():
            try:
                os.chmod(path, tar_info.mode)
            except Exception as e:
                if not psys.is_errno(e, errno.ENOENT):
                    LOG.error("Failed to change permissions of '%s': %s.", path, psys.e(e))
                    self.__ok = False

            try:
                os.utime(path, ( tar_info.mtime, tar_info.mtime ))
            except Exception as e:
                if not psys.is_errno(e, errno.ENOENT):
                    LOG.error("Failed to change access and modification time of '%s': %s.", path, psys.e(e))
                    self.__ok = False
Example #7
0
    def chown(self,user=None,group=None):
        """Change associated owner and group

        'user' and 'group' must be supplied as UID/GID
        numbers (or None to leave the current values
        unchanged).

        *** Note that chown will fail attempting to
        change the owner if the current process is not
        owned by root ***

        This is actually a wrapper to the os.lchmod
        function, so it doesn't follow symbolic links.

        """
        if user is None and group is None:
            # Nothing to do
            return
        if user is None:
            user = -1
        if group is None:
            group = -1
        # Convert to ints
        user = int(user)
        group = int(group)
        # Do chown - note this will fail if the user
        # performing the operation is not root
        os.lchown(self.__path,user,group)
        # Update the stat information
        try:
            self.__st = os.lstat(self.__path)
        except OSError:
            self.__st = None
Example #8
0
def extract_tarball(tarball_full_path, destination_directory=None, progress_update_callback=None):
    if destination_directory is None:
        destination_directory = tarball_full_path[:-8]
    log.debug("extracting %s\n  to %s", tarball_full_path, destination_directory)

    assert not lexists(destination_directory), destination_directory

    with open(tarball_full_path, 'rb') as fileobj:
        if progress_update_callback:
            fileobj = ProgressFileWrapper(fileobj, progress_update_callback)
        with tarfile.open(fileobj=fileobj) as tar_file:
            try:
                tar_file.extractall(path=destination_directory)
            except EnvironmentError as e:
                if e.errno == ELOOP:
                    raise CaseInsensitiveFileSystemError(
                        package_location=tarball_full_path,
                        extract_location=destination_directory,
                        caused_by=e,
                    )
                else:
                    raise

    if sys.platform.startswith('linux') and os.getuid() == 0:
        # When extracting as root, tarfile will by restore ownership
        # of extracted files.  However, we want root to be the owner
        # (our implementation of --no-same-owner).
        for root, dirs, files in os.walk(destination_directory):
            for fn in files:
                p = join(root, fn)
                os.lchown(p, 0, 0)
Example #9
0
def extract(dist):
    """
    Extract a package, i.e. make a package available for linkage. We assume
    that the compressed package is located in the packages directory.
    """
    rec = package_cache()[dist]
    url = rec['urls'][0]
    fname = rec['files'][0]
    assert url and fname
    pkgs_dir = dirname(fname)
    with Locked(pkgs_dir):
        path = fname[:-8]
        rm_rf(path)
        t = tarfile.open(fname)
        t.extractall(path=path)
        t.close()
        if sys.platform.startswith('linux') and os.getuid() == 0:
            # When extracting as root, tarfile will by restore ownership
            # of extracted files.  However, we want root to be the owner
            # (our implementation of --no-same-owner).
            for root, dirs, files in os.walk(path):
                for fn in files:
                    p = join(root, fn)
                    os.lchown(p, 0, 0)
        add_cached_package(pkgs_dir, url, overwrite=True)
Example #10
0
def hostActionCopyConfig(_config):
    global INITRD_ESX_CONF_CHECKSUM
    
    globsToCopy = [
        '/etc/hosts',
        '/etc/resolv.conf',
        '/etc/vmware/esx.conf',
        '/etc/xinetd.d/vmware-authd', # Referenced when turning off ipv6
        '/etc/modprobe.d/blacklist', # Referenced when turning off ipv6
        '/etc/sysconfig/network',
        '/etc/sysconfig/network-scripts/ifcfg-vswif*',
        ]

    # TODO: remove this configcheck, it should be done on bootup.  It's safe
    # to run multiple times though.
    rc = os.system(os.path.join(HOST_ROOT, "usr/sbin/esxcfg-configcheck"))
    assert rc == 0

    for globPath in globsToCopy:
        for srcPath in glob.glob(globPath):
            dstPath = os.path.join(HOST_ROOT, srcPath.lstrip('/'))
            try:
                clonePath(srcPath, dstPath)
                if os.path.islink(srcPath):
                   os.lchown(dstPath, 0, 0)
                else:
                   os.chown(dstPath, 0, 0)

                # XXX Maybe we should turn the files in the initrd into soft
                # links that point at the installed versions of the files...
            except IOError, e:
                log.error("cannot copy %s to %s -- %s" % (
                    srcPath, dstPath, str(e)))
Example #11
0
    def unpack_dir(self, target_dir, callback=None):
        rmode = ""
        self.tar = None
        if self.type == 'tar':
            rmode = 'r:'
        elif self.type == 'targz':
            rmode = 'r:gz'
        elif self.type == 'tarbz2':
            rmode = 'r:bz2'
        elif self.type in ('tarlzma', 'tarxz'):
            self.tar = TarFile.lzmaopen(self.file_path, fileobj=self.fileobj)
        else:
            raise UnknownArchiveType

        if self.tar is None:
            self.tar = tarfile.open(self.file_path, rmode,
                                    fileobj=self.fileobj)

        oldwd = None
        try:
            # Don't fail if CWD doesn't exist (#6748)
            oldwd = os.getcwd()
        except OSError:
            pass
        os.chdir(target_dir)

        uid = os.getuid()
        gid = os.getgid()

        for tarinfo in self.tar:
            if callback:
                callback(tarinfo, extracted=False)

            self.tar.extract(tarinfo)

            # tarfile.extract does not honor umask. It must be honored
            # explicitly. See --no-same-permissions option of tar(1),
            # which is the deafult behaviour.
            #
            # Note: This is no good while installing a pisi package.
            # Thats why this is optional.
            if self.no_same_permissions and not os.path.islink(tarinfo.name):
                os.chmod(tarinfo.name, tarinfo.mode & ~ctx.const.umask)

            if self.no_same_owner:
                if not os.path.islink(tarinfo.name):
                    os.chown(tarinfo.name, uid, gid)
                else:
                    os.lchown(tarinfo.name, uid, gid)

            if callback:
                callback(tarinfo, extracted=True)

        try:
            if oldwd:
                os.chdir(oldwd)
        # Bug #6748
        except OSError:
            pass
        self.close()
Example #12
0
    def migrate_tomcat_libraries(self, instance):
        # remove old links
        for filename in os.listdir(instance.lib_dir):

            if not filename.endswith('.jar'):
                continue

            path = os.path.join(instance.lib_dir, filename)

            if self.verbose:
                print('Removing %s' % path)

            os.remove(path)

        tomcat_dir = '/usr/share/tomcat/lib'

        # create new links
        for filename in os.listdir(tomcat_dir):

            if not filename.endswith('.jar'):
                continue

            source = os.path.join(tomcat_dir, filename)
            dest = os.path.join(instance.lib_dir, filename)

            if self.verbose:
                print('Creating %s' % dest)

            os.symlink(source, dest)
            os.lchown(dest, instance.uid, instance.gid)
Example #13
0
def extract(dist):

    """
    Extract a package, i.e. make a package available for linkage. We assume
    that the compressed package is located in the packages directory.
    """
    rec = package_cache()[dist]
    url = rec["urls"][0]
    fname = rec["files"][0]
    assert url and fname
    pkgs_dir = dirname(fname)
    path = fname[:-8]
    with FileLock(path):
        temp_path = path + ".tmp"
        rm_rf(temp_path)
        with tarfile.open(fname) as t:
            t.extractall(path=temp_path)
        rm_rf(path)
        exp_backoff_fn(os.rename, temp_path, path)
        if sys.platform.startswith("linux") and os.getuid() == 0:
            # When extracting as root, tarfile will by restore ownership
            # of extracted files.  However, we want root to be the owner
            # (our implementation of --no-same-owner).
            for root, dirs, files in os.walk(path):
                for fn in files:
                    p = join(root, fn)
                    os.lchown(p, 0, 0)
        add_cached_package(pkgs_dir, url, overwrite=True)
Example #14
0
def copyown(src, dst):
    """Copy ownership"""
    st = os.lstat(src)
    if DRYRUN:
        print 'chown %d.%d %s' % (st.st_uid, st.st_gid, dst)
    else:
        os.lchown(dst, st.st_uid, st.st_gid)
Example #15
0
File: migrate.py Project: tiran/pki
    def create_link(self, instance, source, dest):

        if self.verbose:
            print('Creating %s' % dest)

        os.symlink(source, dest)
        os.lchown(dest, instance.uid, instance.gid)
Example #16
0
def LChown(path, owner, group):
    error = None
    try:
        os.lchown(path, owner, group)
    except OSError, error:
        print("Exception changing ownership of file " + path + " Error Code: " + str(error.errno) + " Error: " + error.message + error.strerror, file=sys.stderr)
        LG().Log('ERROR', "Exception changing ownership of file " + path + " Error Code: " + str(error.errno) + " Error: " + error.message + error.strerror)
Example #17
0
	def start(self):
		self.path["spool"] = Config.spool
		self.path["spool.real"] = Config.spool+".real"
		if os.path.ismount(self.path["spool"]):
			Logger.warn("Failed to start FS backend, %s is already mounted"%(self.path["spool"]))
			return False
		
		for p in self.path:
			path = self.path[p]
			try:
				os.makedirs(path)
			except OSError, err:
				if err[0] is not errno.EEXIST:
					Logger.exception("Failed to create spool directory: %s"%path)
					return False
			
			try:
				os.lchown(path, Config.uid, Config.gid)
			except OSError:
				Logger.exception("Unable to change file owner for '%s'"%path)
				return False

			if not os.path.exists(path):
				Logger.error("Spool directory %s do not exist"%(path))
				return False
Example #18
0
 def chownTree(self, dirpath, uid, gid):
     """chown the given path and all files and directories under
     it to the given uid/gid."""
     for path, dirs, files in os.walk(dirpath):
         os.lchown(path, uid, gid)
         for filename in files:
             os.lchown(os.path.join(path, filename), uid, gid)
Example #19
0
def chown(path, uid, gid):
    """Attempt to change the owner/group of the given file/directory using
       os.lchown(). If this fails due to insufficient permissions, display
       an appropriate error message and exit. Otherwise, raise the error."""
    try:
        # Use lchown so we do not follow symbolic links, just change the
        # target as specified by the caller.
        os.lchown(path, uid, gid)
        # Note that it is possible the destination volume was mounted with
        # the MNT_IGNORE_OWNERSHIP flag, in which case everything we create
        # there will be owned by the _unknown user and group, no matter what
        # we might want it to be. This is built into the XNU kernel.
    except OSError, e:
        if e.errno == errno.EPERM:
            # Strangely root has problems changing symlinks that point
            # to non-existent entries, need to filter out and ignore
            # (we are most likely copying to an external disk anyway,
            # in which case all files are owned by the _unknown user).
            mode = os.lstat(path)[stat.ST_MODE]
            if not stat.S_ISLNK(mode):
                # Sometimes mysteriously fails to chown directories.
                # Try again in one second; if it fails again ignore
                # the problem and move on.
                time.sleep(1)
                try:
                    os.chown(path, uid, gid)
                except OSError:
                    pass
        else:
            raise e
Example #20
0
def lchown(space, path, uid, gid):
    check_uid_range(space, uid)
    check_uid_range(space, gid)
    try:
        os.lchown(path, uid, gid)
    except OSError, e:
        raise wrap_oserror(space, e, path)
Example #21
0
    def _getFilename(self, name, expire = None, uid=None, gid=None, suffix=".png"):
        old_mask = os.umask(0)
        basename = base64.urlsafe_b64encode(name.encode("utf-8"))
        pathname = os.path.join(siteconfig.htdocs_dir, "generated_images")

        user = base64.urlsafe_b64encode(self._user.login.encode("utf-8"))
        pathname = os.path.normpath(os.path.join(pathname, user))

        try:
            os.mkdir(pathname, 0755)
        except: pass
        if uid != None and gid != None:
            os.lchown(pathname, uid, gid)

        self._remove_old_chart_files(os.path.join(pathname, basename), expire)

        fd, self._filename = tempfile.mkstemp(prefix = basename + "_", suffix = suffix, dir = pathname)
        if uid != None and gid != None:
            os.lchown(self._filename, uid, gid)

        os.chmod(self._filename, 0644)

        self._href = urllib.quote("confutatis/generated_images/%s" % (user or "") + "/" + os.path.basename(self._filename))
        os.umask(old_mask)

        return self._filename
Example #22
0
 def restore_attrs(self, path, item, symlink=False, fd=None):
     xattrs = item.get(b'xattrs')
     if xattrs:
             for k, v in xattrs.items():
                 try:
                     xattr.setxattr(fd or path, k, v)
                 except OSError as e:
                     if e.errno != errno.ENOTSUP:
                         raise
     uid = gid = None
     if not self.numeric_owner:
         uid = user2uid(item[b'user'])
         gid = group2gid(item[b'group'])
     uid = uid or item[b'uid']
     gid = gid or item[b'gid']
     # This code is a bit of a mess due to os specific differences
     try:
         if fd:
             os.fchown(fd, uid, gid)
         else:
             os.lchown(path, uid, gid)
     except OSError:
         pass
     if fd:
         os.fchmod(fd, item[b'mode'])
     elif not symlink:
         os.chmod(path, item[b'mode'])
     elif has_lchmod:  # Not available on Linux
         os.lchmod(path, item[b'mode'])
     if fd and utime_supports_fd:  # Python >= 3.3
         os.utime(fd, None, ns=(item[b'mtime'], item[b'mtime']))
     elif utime_supports_fd:  # Python >= 3.3
         os.utime(path, None, ns=(item[b'mtime'], item[b'mtime']), follow_symlinks=False)
     elif not symlink:
         os.utime(path, (item[b'mtime'] / 10**9, item[b'mtime'] / 10**9))
Example #23
0
def link_system_python_packages():
    packages = OPTS.system_packages.split()
    python_paths = [x / 'site-packages' for x in OPTS.venv.joinpath("lib").glob('python3*')]

    files_to_clean = []
    files_to_link = []
    uid = pwd.getpwnam(OPTS.user)[2]
    gid = grp.getgrnam(OPTS.group)[2]

    for package in packages:
        try:
            pkg = __import__(package, globals())
        except ImportError:
            exit_with_error(1, "Couldn't find python package %r from the system" % (package,))
        pkg_src, _, _ = pkg.__file__.rpartition('/')
        pkg_path, _, pkg_name = pkg_src.rpartition('/')
        sources = Path(pkg_path).glob(pkg_name + '*')
        for dst in python_paths:
            files_to_clean.extend(dst.glob(pkg_name + '*'))
            files_to_link.extend((dst / file_.name, file_) for file_ in sources)

    for file_ in files_to_clean:
        debug("removing file or dir '%s'" % (file_,))
        try:
            file_.unlink()
        except OSError:
            rmtree(str(file_))
    for dst, src in files_to_link:
        debug("creating symlink '%s' -> '%s'" % (dst, src))
        dst.symlink_to(src)
        lchown(str(dst), uid, gid)
def LChown(path, owner, group):
    error = None
    try:
        os.lchown(path, owner, group)
    except OSError, error:
        Print("Exception changing ownership of file " + path  + " Error: " + str(error), file=sys.stderr)
        LG().Log('ERROR', "Exception changing ownership of file " + path  + " Error: " + str(error))
 def process_file(self, source, destination, root, link=False, **options):
     dry_run = options.get('dry_run', False)
     interactive = options.get('interactive', False)
     destination = os.path.abspath(os.path.join(root, destination))
     if not dry_run:
         # Get permission bits and ownership of `root`.
         try:
             root_stat = os.stat(root)
         except os.error:
             mode = 0777  # Default for `os.makedirs` anyway.
             uid = gid = None
         else:
             mode = root_stat.st_mode
             uid, gid = root_stat.st_uid, root_stat.st_gid
         destination_dir = os.path.dirname(destination)
         try:
             # Recursively create all the required directories, attempting
             # to use the same mode as `root`.
             os.makedirs(destination_dir, mode)
         except os.error:
             # This probably just means the leaf directory already exists,
             # but if not, we'll find out when copying or linking anyway.
             pass
         else:
             if None not in (uid, gid) and hasattr(os, 'lchown'):
                 os.lchown(destination_dir, uid, gid)
     if link:
         success = self.link_file(source, destination, interactive, dry_run)
     else:
         success = self.copy_file(source, destination, interactive, dry_run)
     if success and None not in (uid, gid) and hasattr(os, 'lchown'):
         # Try to use the same ownership as `root`.
         os.lchown(destination, uid, gid)
Example #26
0
def extract_tarball(tarball_full_path, destination_directory=None, progress_update_callback=None):
    if destination_directory is None:
        if tarball_full_path.endswith('.tar.bz2'):
            destination_directory = tarball_full_path[:-8]
        else:
            destination_directory = tarball_full_path.splitext()[0]
    log.debug("extracting %s\n  to %s", tarball_full_path, destination_directory)

    # the most common reason this happens is due to hard-links, windows thinks
    #    files in the package cache are in-use. rm_rf should have moved them to
    #    have a .conda_trash extension though, so it's ok to just write into
    #    the same existing folder.
    if not path_is_clean(destination_directory):
        log.debug("package folder {} was not empty, but we're writing there."
                  .format(destination_directory))

    conda_package_handling.api.extract(tarball_full_path, dest_dir=destination_directory)

    if sys.platform.startswith('linux') and os.getuid() == 0:
        # When extracting as root, tarfile will by restore ownership
        # of extracted files.  However, we want root to be the owner
        # (our implementation of --no-same-owner).
        for root, dirs, files in os.walk(destination_directory):
            for fn in files:
                p = join(root, fn)
                os.lchown(p, 0, 0)
Example #27
0
    def addFileToAlbum(self, photo):
        """
        add a file to an album, the albumid must be previously stored in the LycheePhoto parameter
        Parameters:
        - photo: a valid LycheePhoto object
        Returns True if everything went ok
        """
        res = False

        try:
            # copy photo
            if self.conf['link']:
                os.symlink(photo.srcfullpath, photo.destfullpath)
            else:
                shutil.copy(photo.srcfullpath, photo.destfullpath)
            # adjust right (chmod/chown)
            os.lchown(photo.destfullpath, self.conf['uid'], self.conf['gid'])

            if not(self.conf['link']):
                st = os.stat(photo.destfullpath)
                os.chmod(photo.destfullpath, st.st_mode | stat.S_IRWXU | stat.S_IRWXG)
            else:
                st = os.stat(photo.srcfullpath)
                os.chmod(photo.srcfullpath, st.st_mode | stat.S_IROTH)

            res = self.dao.addFileToAlbum(photo)

        except Exception:
            print "addFileToAlbum", Exception
            traceback.print_exc()
            res = False

        return res
Example #28
0
def initialize_home_directory():
    """
        initialize_home_directory

        If the home folder is not found, initialize it.
    """

    if os.path.exists(HOME):
        return

    os.mkdir(HOME, 0770)

    # some sudo calls change the euid, uid and ruid to 0, which might not be
    # accessible later when running as a user process. This, for some reason
    # happens on certain MacOS systems
    if "SUDO_UID" in os.environ:
        uid = int(os.environ["SUDO_UID"])
        gid = int(os.environ["SUDO_GID"])
        os.lchown(HOME, uid, gid)

    settings_file = os.path.join(HOME, "settings.json")

    initialize_default_settings(settings_file)

    return
Example #29
0
    def unpack_dir(self, target_dir):
        rmode = ""
        if self.type == 'tar':
            rmode = 'r:'
        elif self.type == 'targz':
            rmode = 'r:gz'
        elif self.type == 'tarbz2':
            rmode = 'r:bz2'
        elif self.type == 'tarlzma':
            rmode = 'r:'
            self.file_path = self.file_path.rstrip(ctx.const.lzma_suffix)
            ret, out, err = util.run_batch("lzma d %s %s" % (self.file_path + ctx.const.lzma_suffix,
                                                             self.file_path))
            if ret != 0:
                raise LZMAError(err)
        else:
            raise ArchiveError(_("Archive type not recognized"))

        self.tar = tarfile.open(self.file_path, rmode)
        oldwd = os.getcwd()
        os.chdir(target_dir)

        uid = os.getuid()
        gid = os.getgid()

        install_tar_path = util.join_path(ctx.config.tmp_dir(), ctx.const.install_tar)
        for tarinfo in self.tar:
            # Installing packages (especially shared libraries) is a
            # bit tricky. You should also change the inode if you
            # change the file, cause the file is opened allready and
            # accessed. Removing and creating the file will also
            # change the inode and will do the trick (in fact, old
            # file will be deleted only when its closed).
            # 
            # Also, tar.extract() doesn't write on symlinks... Not any
            # more :).
            if self.file_path == install_tar_path:
                if os.path.isfile(tarinfo.name) or os.path.islink(tarinfo.name):
                    try:
                        os.unlink(tarinfo.name)
                    except OSError, e:
                        ctx.ui.warning(e)

            self.tar.extract(tarinfo)

            # tarfile.extract does not honor umask. It must be honored explicitly.
            # see --no-same-permissions option of tar(1), which is the deafult
            # behaviour.
            #
            # Note: This is no good while installing a pisi package. Thats why
            # this is optional.
            if self.no_same_permissions and not os.path.islink(tarinfo.name):
                os.chmod(tarinfo.name, tarinfo.mode & ~ctx.const.umask)

            if self.no_same_owner:
                if not os.path.islink(tarinfo.name):
                    os.chown(tarinfo.name, uid, gid)
                else:
                    os.lchown(tarinfo.name, uid, gid)
Example #30
0
def _create(data):
    for path, attr in sorted(data.files.iteritems()):
        _mk_file(data, path, attr['source'], attr['content'], attr['target'])
    for path in reversed(data.created):
        attr = data.files[path]
        if not attr.get('target', None):
            os.chmod(path, attr['mode'])
        os.lchown(path, attr['uid'], attr['gid'])
Example #31
0
    def _set_attributes(opts, path):
        """Set file attributes on a given path.

        Args:
            path: file/directory path
        """
        try:
            if opts.owner != -1 or opts.group != -1:
                os.lchown(path, opts.owner, opts.group)
            if opts.mode is not None and not os.path.islink(path):
                os.chmod(path, opts.mode)
        except OSError as e:
            raise IpcCommandError(
                f'failed setting file attributes: {path!r}: {e.strerror}')
Example #32
0
 def restore_attrs(self, path, item, symlink=False, fd=None):
     xattrs = item.get(b'xattrs', {})
     for k, v in xattrs.items():
         try:
             xattr.setxattr(fd or path, k, v, follow_symlinks=False)
         except OSError as e:
             if e.errno not in (errno.ENOTSUP, errno.EACCES, ):
                 # only raise if the errno is not on our ignore list:
                 # ENOTSUP == xattrs not supported here
                 # EACCES == permission denied to set this specific xattr
                 #           (this may happen related to security.* keys)
                 raise
     uid = gid = None
     if not self.numeric_owner:
         uid = user2uid(item[b'user'])
         gid = group2gid(item[b'group'])
     uid = item[b'uid'] if uid is None else uid
     gid = item[b'gid'] if gid is None else gid
     # This code is a bit of a mess due to os specific differences
     try:
         if fd:
             os.fchown(fd, uid, gid)
         else:
             os.lchown(path, uid, gid)
     except OSError:
         pass
     if fd:
         os.fchmod(fd, item[b'mode'])
     elif not symlink:
         os.chmod(path, item[b'mode'])
     elif has_lchmod:  # Not available on Linux
         os.lchmod(path, item[b'mode'])
     mtime = bigint_to_int(item[b'mtime'])
     if b'atime' in item:
         atime = bigint_to_int(item[b'atime'])
     else:
         # old archives only had mtime in item metadata
         atime = mtime
     if fd:
         os.utime(fd, None, ns=(atime, mtime))
     else:
         os.utime(path, None, ns=(atime, mtime), follow_symlinks=False)
     acl_set(path, item, self.numeric_owner)
     # Only available on OS X and FreeBSD
     if has_lchflags and b'bsdflags' in item:
         try:
             os.lchflags(path, item[b'bsdflags'])
         except OSError:
             pass
Example #33
0
File: ops.py Project: chutz/pkgcore
def default_ensure_perms(d1, d2=None):
    """Enforce a fs objects attributes on the livefs.

    Attributes enforced are permissions, mtime, uid, gid.

    :param d2: if not None, an fs object for what's on the livefs now
    :return: True on success, else an exception is thrown
    :raise EnvironmentError: if fs object attributes can't be enforced
    """

    m, o, g, t = d1.mode, d1.uid, d1.gid, d1.mtime
    if o is None:
        o = -1
    if g is None:
        g = -1
    if d2 is None:
        do_mode, do_chown, do_mtime = True, True, True
    else:

        do_mode = False
        try:
            if fs.isdir(d1) and fs.isdir(d2):
                # if it's preexisting, keep it's perms.
                do_mode = False
            else:
                do_mode = (m is not None and m != d2.mode)
        except AttributeError:
            # yes.  this _is_ stupid.  vdb's don't always store all attributes
            do_mode = False

        do_chown = False
        try:
            do_chown = (o != d2.uid or g != d2.gid)
        except AttributeError:
            do_chown = True

        try:
            do_mtime = (t != d2.mtime)
        except AttributeError:
            do_mtime = True

    if do_chown and (o != -1 or g != -1):
        os.lchown(d1.location, o, g)
    if not fs.issym(d1):
        if do_mode and m is not None:
            os.chmod(d1.location, m)
        if do_mtime and t is not None:
            os.utime(d1.location, (t, t))
    return True
Example #34
0
 def remap_gid(self, src, dest):
     group = self.group[src]
     del self.group[src]
     group.change_gid(dest)
     self.group[group.gid] = group
     for passwd in self.passwd.values():
         if passwd.gid == src:
         	passwd.change_gid(dest)
     for root, dirs, files in os.walk(self.basedir):
         for item in dirs + files:
             stat = os.lstat(os.path.join(root, item))
             if stat.st_gid == src:
                 os.lchown(os.path.join(root, item), stat.st_uid, dest)
                 if not os.path.islink(os.path.join(root, item)):
                 	os.chmod(os.path.join(root, item), stat.st_mode)
Example #35
0
 def recovery_stat(self, object_path, lstat):
     #os.lchmod(object_path, lstat.st_mode)  AttributeError: 'module' object has no attribute 'lchmod'
     try :
         time = lstat.st_atime, lstat.st_mtime
         os.utime(object_path, time)
     except OSError:
         pass
     try:
         os.chmod(object_path, S_IMODE(lstat.st_mode))
     except OSError:
         pass
     try:
         os.lchown(object_path, lstat.st_uid, lstat.st_gid)
     except OSError:
         pass # doplnit printy / handle exceptetion
Example #36
0
def move(src, dst):
    st = os.lstat(src)

    is_symlink = stat.S_ISLNK(st.st_mode)

    if os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(os.path.abspath(src)))

    if is_symlink:
        linkto = os.readlink(src)
        os.symlink(linkto, dst)
        os.unlink(src)
    else:
        shutil.move(src, dst)
        os.lchown(dst, st.st_uid, st.st_gid)
Example #37
0
    def update_container_ids(self, container_name):
        """
        By default, the container are checked out as root. This method sets the uid and
        gid of all the container related files to 1000 (UID) and 1000 (GID).

        Parameters:
        container_name (str): the name of the container
        """
        self.logger.info("Update the UID and GID of the rootfs")
        os.chown(PATH_APPS + '/' + container_name, CONTAINER_UID, CONTAINER_GID)
        for dirpath, dirnames, filenames in os.walk(PATH_APPS + '/' + container_name):
            for dname in dirnames:
                os.lchown(os.path.join(dirpath, dname), CONTAINER_UID, CONTAINER_GID)
            for fname in filenames:
                os.lchown(os.path.join(dirpath, fname), CONTAINER_UID, CONTAINER_GID)
Example #38
0
def _set_attributes(options, path):
	"""Sets attributes the file/dir at given |path|.

	Args:
		options: object which has |owner|, |group| and |mode| fields.
			|owner| is int value representing uid. Similary |group|
			represents gid.
			If -1 is set, just unchanged.
			|mode| is the bits of permissions.
		path: File/directory path.
	"""
	if options.owner != -1 or options.group != -1:
		os.lchown(path, options.owner, options.group)
	if options.mode is not None:
		os.chmod(path, options.mode)
Example #39
0
def editor_save_view(request, site_id):
    site = get_object_or_404(Site, id=site_id)
    if not request.user.is_superuser and not site.group.users.filter(
            id=request.user.id).exists():
        raise PermissionDenied

    requested_path = request.GET.get("name", "")
    path = os.path.abspath(os.path.join(site.path, requested_path))

    if not path.startswith(site.path):
        return JsonResponse({
            "error": "Invalid or nonexistent file!",
            "path": path
        })

    set_perms = False

    if not os.path.isfile(path):
        if os.path.exists(path):
            return JsonResponse({
                "error": "Invalid or nonexistent file!",
                "path": path
            })
        if not request.POST.get("force", False):
            return JsonResponse({
                "error": "The file you are editing does not exist anymore!",
                "path": path,
                "force": True
            })
        else:
            set_perms = True

    if (path.rstrip("/") + "/").startswith(site.logs_path + "/"):
        return JsonResponse({
            "error": "You cannot edit your site's log file.",
            "path": path
        })

    with switch_to_site_user(site):
        with open(path, "w", encoding="utf-8") as f:
            f.write(request.POST.get("contents"))

        if set_perms:
            st = os.lstat(path)
            os.lchown(path, site.user.id, site.group.id)
            os.chmod(path, st.st_mode | stat.S_IRGRP | stat.S_IWGRP)

    return JsonResponse({"success": True})
Example #40
0
    def _set_perms(self, entry, path=None):
        """ set permissions on the given entry, or on the given path
        according to the given entry """
        if path is None:
            path = entry.get("name")

        rv = True
        if os.geteuid() == 0:
            if entry.get("owner") and entry.get("group"):
                try:
                    self.logger.debug(
                        "POSIX: Setting ownership of %s to %s:%s" %
                        (path, self._norm_entry_uid(entry),
                         self._norm_entry_gid(entry)))
                    os.lchown(path, self._norm_entry_uid(entry),
                              self._norm_entry_gid(entry))
                except (OSError, KeyError):
                    self.logger.error(
                        'POSIX: Failed to change ownership of %s' % path)
                    rv = False
                    if sys.exc_info()[0] == KeyError:
                        os.lchown(path, 0, 0)
        else:
            self.logger.debug("POSIX: Run as non-root, not setting ownership")

        if entry.get("mode"):
            wanted_mode = int(entry.get('mode'), 8)
            if entry.get('dev_type'):
                wanted_mode |= device_map[entry.get('dev_type')]
            try:
                self.logger.debug("POSIX: Setting mode on %s to %s" %
                                  (path, oct_mode(wanted_mode)))
                os.chmod(path, wanted_mode)
            except (OSError, KeyError):
                self.logger.error('POSIX: Failed to change mode on %s' % path)
                rv = False

        if entry.get('mtime'):
            try:
                os.utime(entry.get('name'),
                         (int(entry.get('mtime')), int(entry.get('mtime'))))
            except OSError:
                self.logger.error("POSIX: Failed to set mtime of %s" % path)
                rv = False

        rv &= self._set_secontext(entry, path=path)
        rv &= self._set_acls(entry, path=path)
        return rv
Example #41
0
def setup_service_account(irods_config, irods_user, irods_group):
    l = logging.getLogger(__name__)
    l.info(irods.lib.get_header('Setting up the service account'))

    if irods_group not in [g.gr_name for g in grp.getgrall()]:
        l.info('Creating Service Group: %s', irods_group)
        irods.lib.execute_command(['groupadd', '-r', irods_group])
    else:
        l.info('Existing Group Detected: %s', irods_group)

    if irods.lib.execute_command_permissive(['id', irods_user])[2] != 0:
        l.info('Creating Service Account: %s', irods_group)
        irods.lib.execute_command([
            'useradd', '-r', '-d', irods_config.irods_directory, '-M', '-s',
            '/bin/bash', '-g', irods_group, '-c', 'iRODS Administrator', '-p',
            '!', irods_user
        ])
    else:
        l.info('Existing Account Detected: %s', irods_user)

    with open(irods_config.service_account_file_path, 'wt') as f:
        print('IRODS_SERVICE_ACCOUNT_NAME=%s' % (irods_user), file=f)
        print('IRODS_SERVICE_GROUP_NAME=%s' % (irods_group), file=f)

    l.info('Setting owner of %s to %s:%s', irods_config.irods_directory,
           irods_user, irods_group)
    for (root, _, files) in os.walk(irods_config.irods_directory):
        os.lchown(root,
                  pwd.getpwnam(irods_user).pw_uid,
                  grp.getgrnam(irods_group).gr_gid)
        for filename in files:
            os.lchown(os.path.join(root, filename),
                      pwd.getpwnam(irods_user).pw_uid,
                      grp.getgrnam(irods_group).gr_gid)

    l.info('Setting owner of %s to %s:%s', irods_config.config_directory,
           irods_user, irods_group)
    for (root, _, files) in os.walk(irods_config.config_directory):
        os.lchown(root,
                  pwd.getpwnam(irods_user).pw_uid,
                  grp.getgrnam(irods_group).gr_gid)
        for filename in files:
            os.lchown(os.path.join(root, filename),
                      pwd.getpwnam(irods_user).pw_uid,
                      grp.getgrnam(irods_group).gr_gid)

    l.debug('Setting uid bit on %s', irods.paths.genosauth_path())
    os.chmod(
        irods.paths.genosauth_path(), stat.S_ISUID
        | stat.S_IRUSR
        | stat.S_IXUSR
        | stat.S_IRGRP
        | stat.S_IXGRP
        | stat.S_IROTH
        | stat.S_IXOTH)

    #owner of top-level directory changed, clear the cache
    irods_config.clear_cache()
Example #42
0
def extract_tarball(tarball_full_path,
                    destination_directory=None,
                    progress_update_callback=None):
    if destination_directory is None:
        destination_directory = tarball_full_path[:-8]
    log.debug("extracting %s\n  to %s", tarball_full_path,
              destination_directory)

    # the most common reason this happens is due to hard-links, windows thinks
    #    files in the package cache are in-use. rm_rf should have moved them to
    #    have a .conda_trash extension though, so it's ok to just write into
    #    the same existing folder.
    if not path_is_clean(destination_directory):
        log.debug(
            "package folder {} was not empty, but we're writing there.".format(
                destination_directory))

    with open(tarball_full_path, 'rb') as fileobj:
        if progress_update_callback:
            fileobj = ProgressFileWrapper(fileobj, progress_update_callback)
        with tarfile.open(fileobj=fileobj) as tar_file:
            if context.safety_checks:
                for member in tar_file.getmembers():
                    if (os.path.isabs(member.name) or not os.path.realpath(
                            member.name).startswith(os.getcwd())):
                        raise CondaFileIOError(
                            tarball_full_path,
                            "contains unsafe path: {}".format(member.name))
            try:
                tar_file.extractall(path=destination_directory)
            except EnvironmentError as e:
                if e.errno == ELOOP:
                    raise CaseInsensitiveFileSystemError(
                        package_location=tarball_full_path,
                        extract_location=destination_directory,
                        caused_by=e,
                    )
                else:
                    raise

    if sys.platform.startswith('linux') and os.getuid() == 0:
        # When extracting as root, tarfile will by restore ownership
        # of extracted files.  However, we want root to be the owner
        # (our implementation of --no-same-owner).
        for root, dirs, files in os.walk(destination_directory):
            for fn in files:
                p = join(root, fn)
                os.lchown(p, 0, 0)
Example #43
0
 def _retry_request(self, rsrc_id):
     """Force re-evaluation of a request.
     """
     # XXX(boysson): Duplicate of _base_service.clt_update_request
     request_lnk = os.path.join(self._service_rsrc_dir, rsrc_id)
     _LOGGER.debug('Updating %r', rsrc_id)
     # NOTE(boysson): This does the equivalent of a touch on the symlink
     try:
         os.lchown(
             request_lnk,
             os.getuid(),
             os.getgid()
         )
     except OSError as err:
         if err.errno != errno.ENOENT:
             raise
Example #44
0
    def clt_update_request(self, req_id):
        """Update an existing request.

        This should only be called by the client instance.
        """
        svc_req_lnk = os.path.join(self._rsrc_dir, req_id)
        _LOGGER.debug('Updating %r: %r', req_id, svc_req_lnk)
        # Remove any reply if it exists
        fs.rm_safe(os.path.join(svc_req_lnk, _REP_FILE))

        # NOTE(boysson): This does the equivalent of a touch on the symlink
        try:
            os.lchown(svc_req_lnk, os.getuid(), os.getgid())
        except OSError as err:
            if err.errno != errno.ENOENT:
                raise
Example #45
0
def SetPosix(path, meta):
    amroot = os.geteuid() == 0
    try:
        os.lchown(path, meta[TAR_UID_KEY], meta[TAR_GID_KEY])
    except os.error as e:
        # If we're not root, we can't do the chown
        if e[0] != errno.EPERM and amroot:
            raise e
    os.lchmod(path, meta[TAR_MODE_KEY])
    if meta[TAR_FLAGS_KEY] != 0:
        try:
            os.lchflags(path, meta[TAR_FLAGS_KEY])
        except os.error as e:
            # If we're not root, we can't do some of this, either
            if e[0] != errno.EPERM and amroot:
                raise e
Example #46
0
    def setattr(cls, path, adct):
        """set file attributes

        @adct is a dict, where 'own', 'mode' and 'times'
        keys are looked for and values used to perform
        chown, chmod or utimes on @path.
        """
        own = adct.get('own')
        if own:
            os.lchown(path, *own)
        mode = adct.get('mode')
        if mode:
            os.chmod(path, stat.S_IMODE(mode))
        times = adct.get('times')
        if times:
            os.utime(path, times)
Example #47
0
 def _replaceDirUidGidImpl(dirname, uidDict, gidDict, ignoreAbsList):
     for fb in os.listdir(dirname):
         f = os.path.join(dirname, fb)
         if any(x for x in ignoreAbsList if fnmatch.fnmatch(f, x)):
             continue
         if VccUtil.isTrivalDir(f):
             VccUtil._replaceDirUidGidImpl(f, uidDict, gidDict, ignoreAbsList)
         elif VccUtil.isTrivalFile(f):
             pass
         else:
             assert False
         userId = os.lstat(f).st_uid
         groupId = os.lstat(f).st_gid
         userId = uidDict.get(userId, userId)
         groupId = gidDict.get(groupId, groupId)
         os.lchown(f, userId, groupId)
Example #48
0
File: util.py Project: zdzichu/pki
def chown(path, uid, gid):
    """
    Change ownership of a file, link, or folder recursively.
    """

    if os.path.islink(path):
        os.lchown(path, uid, gid)
    else:
        os.chown(path, uid, gid)

    if not os.path.isdir(path):
        return

    for item in os.listdir(path):
        itempath = os.path.join(path, item)
        chown(itempath, uid, gid)
Example #49
0
 def preparePersistDir(dirname, uid, gid, mode):
     if not os.path.exists(dirname):
         os.makedirs(dirname, mode)
         if os.getuid() != uid or os.getpid() != gid:
             os.chown(dirname, uid, gid)
     else:
         st = os.stat(dirname)
         if stat.S_IMODE(st.st_mode) != mode:
             os.chmod(dirname, mode)
         if st.st_uid != uid or st.st_gid != gid:
             os.chown(dirname, uid, gid)
             for root, dirs, files in os.walk(dirname):
                 for d in dirs:
                     os.lchown(os.path.join(root, d), uid, gid)
                 for f in files:
                     os.lchown(os.path.join(root, f), uid, gid)
Example #50
0
def lchown(path, user=-1, group=-1):
    """
    Change the owner/group of a path, raises an OSError if the
    ownership change fails.

    :param user: user to change
    :type user: int or str
    :param group: group to change
    :type group: int or str
    """
    if isinstance(user, str):
        import pwd

        entry = pwd.getpwnam(user)
        if not entry:
            raise OSError("Unknown user %r" % user)
        user = entry[2]
    if isinstance(group, str):
        import grp

        entry = grp.getgrnam(group)
        if not entry:
            raise OSError("Unknown group %r" % group)
        group = entry[2]
    return os.lchown(path, user, group)
Example #51
0
def _link_fetch(fh, changed, opts):

    linkpath = os.path.join(opts.dest_dir, fh.fpath)

    if not os.path.exists(linkpath):
        log.debug("Creating symlink '%s'->'%s'", linkpath, fh.link_target)
        if not opts.quiet:
            print("L: (create) %s -> %s" % (linkpath, fh.link_target))
        os.symlink(fh.link_target, linkpath)
        opts.stats.link_contents_differed += 1

    else:
        log.debug("Path '%s' exists in the filesystem", linkpath)
        if not os.path.islink(linkpath):
            raise NonLinkFoundAtLinkLocationError(
                "Non-symlink found where we want a symlink ('%s')" % linkpath)

        else:
            # Symlink found. Check it.
            curtgt = os.readlink(linkpath)
            # Create or move the symlink.
            if curtgt != fh.link_target:
                changed.contents = True
                log.debug("Moving symlink '%s'->'%s'", linkpath,
                          fh.link_target)
                if not opts.quiet:
                    print("L: (move) %s -> %s" % (linkpath, fh.link_target))
                os.symlink(fh.link_target, linkpath)
                opts.stats.link_contents_differed += 1

    expect_uid = fh.uid
    expect_gid = fh.gid

    lstat = os.lstat(linkpath)
    if lstat.st_uid != expect_uid or lstat.st_gid != expect_gid:
        changed.uidgid = True
        log.debug("Changing link '%s' ownership to %s/%s", linkpath,
                  expect_uid, expect_gid)
        os.lchown(linkpath, expect_uid, expect_gid)

    if lstat.st_mode != fh.mode:
        changed.mode = True
        log.debug("Changing link '%s' mode to %06o", linkpath, fh.mode)
        os.lchmod(linkpath, fh.mode)

    if changed.mode or changed.uidgid:
        opts.stats.link_metadata_differed += 1
Example #52
0
def fix_permissions(site):
    for root, dirs, files in os.walk(site.path):
        dirs[:] = [d for d in dirs if not d == ".ssh"]
        for f in files + dirs:
            path = os.path.join(root, f)
            try:
                st = os.lstat(path)
            except:
                client.captureException()
                continue
            os.lchown(path, site.user.id, site.group.id)
            if stat.S_ISLNK(st.st_mode):
                pass
            elif stat.S_ISDIR(st.st_mode):
                os.chmod(path, st.st_mode | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP)
            else:
                os.chmod(path, st.st_mode | stat.S_IRGRP | stat.S_IWGRP)
Example #53
0
def shift_path(path,
               uid_mappings,
               gid_mappings,
               nobody,
               uid_memo,
               gid_memo,
               dry_run=False,
               verbose=False):
    stat = os.lstat(path)
    uid = stat.st_uid
    gid = stat.st_gid
    target_uid = find_target_id(uid, uid_mappings, nobody, uid_memo)
    target_gid = find_target_id(gid, gid_mappings, nobody, gid_memo)
    if verbose:
        print_chown(path, uid, gid, target_uid, target_gid)
    if not dry_run:
        os.lchown(path, target_uid, target_gid)
def copy_file(basedir, filepath, dstdir, uid=None, gid=None):
    import shutil
    subdir = os.path.relpath(os.path.dirname(filepath), basedir)
    if subdir is not '.':
        dstdir = os.path.join(dstdir, subdir)
        mkdir_p(dstdir)

    dstfilepath = os.path.join(dstdir, os.path.basename(filepath))
    if os.path.exists(dstfilepath):
        dstfilepath = make_up_filename(dstfilepath)
        shutil.copyfile(filepath, dstfilepath)
    else:
        shutil.copy(filepath, dstdir)
    print('copying: {} --> {}'.format(filepath, dstdir))
    if uid and gid:
        os.lchown(dstdir, uid, gid)
        os.lchown(dstfilepath, uid, gid)
Example #55
0
def regen_ss_file():
    # this is only used for Kerberos auth at the moment.
    # it identifies XMLRPC requests from Apache that have already
    # been cleared by Kerberos.
    ssfile = "/var/lib/cobbler/web.ss"
    fd = open("/dev/urandom", 'rb')
    data = fd.read(512)
    fd.close()

    fd = os.open(ssfile, os.O_CREAT | os.O_RDWR, 0o600)
    os.write(fd, binascii.hexlify(data))
    os.close(fd)

    http_user = utils.get_http_user()
    os.lchown("/var/lib/cobbler/web.ss", pwd.getpwnam(http_user)[2], -1)

    return 1
Example #56
0
    def replace_with_link(self, instance, filename, target):

        source = os.path.join(instance.conf_dir, filename)

        # if source is already a link, skip
        if os.path.islink(source):
            return

        self.backup(source)

        # if source already exists, remove it
        if os.path.exists(source):
            os.remove(source)

        # link source to target
        os.symlink(target, source)
        os.lchown(source, instance.uid, instance.gid)
Example #57
0
def extract_tarball(tarball_full_path, destination_directory=None):
    if destination_directory is None:
        destination_directory = tarball_full_path[:-8]
    log.debug("extracting %s\n  to %s", tarball_full_path, destination_directory)

    assert not lexists(destination_directory), destination_directory

    with tarfile.open(tarball_full_path) as t:
        t.extractall(path=destination_directory)
    if sys.platform.startswith('linux') and os.getuid() == 0:
        # When extracting as root, tarfile will by restore ownership
        # of extracted files.  However, we want root to be the owner
        # (our implementation of --no-same-owner).
        for root, dirs, files in os.walk(destination_directory):
            for fn in files:
                p = join(root, fn)
                os.lchown(p, 0, 0)
    def create_home(self, user_info):
        group = user_info["profile"]
        if group == "admin":
            group = "admins"
        uid = user_info["uid"]
        nethome = os.path.join(self.nethome_path, group, uid)

        if not os.path.exists(nethome):
            userid = int(user_info["uidNumber"])
            nobody_id = int(pwd.getpwnam("nobody").pw_uid)
            usergid = int(grp.getgrnam("nogroup").gr_gid)
            #fix umask for fix correct permission
            prevmask = os.umask(0)
            os.mkdir(nethome, 0o2770)
            #shutils.copytree("/etc/skel/UserFiles",nethome,symlinks=True)
            #p1=subprocess.Popen(["rsync","-rltgD","/etc/skel-net/",pipes.quote(nethome)])
            command = 'rsync -rltgD /etc/skel-net/ "%s"' % nethome
            p1 = os.system(command)

            #out = p1.communicate()
            '''
				#chown -R user:guser
				#chmod 770 for all directories
				#chmod 660 for all files
			'''
            os.lchown(nethome, nobody_id, usergid)
            for base, directories, files in os.walk(nethome):
                for directori in directories:
                    auxpath = os.path.join(base, directori)
                    os.lchown(auxpath, userid, usergid)
                    os.chmod(auxpath, 0o2770)

                for auxfile in files:
                    auxpath = os.path.join(base, auxfile)
                    os.chown(auxpath, userid, usergid)
                    os.chmod(auxpath, 0o660)
            # for

            # restore old umask
            os.chmod(nethome, 0o2770)
            os.umask(prevmask)
            for acl in self.home_acls:
                #command='setfacl %s "%s"'%(acl%str(userid),pipes.quote(nethome))
                command = 'setfacl %s "%s"' % (acl % str(userid), nethome)
                os.system(command)
        return nethome
Example #59
0
def oscheck():
    try:
        pwd.getpwnam("mysql")
    except:
        os.system("groupadd mysql")
        os.system("useradd -g mysql -d /opt/mysql -s /sbin/nologin mysql")
        print "create mysql user ok"

    user = pwd.getpwnam("mysql")

    if ((os.path.isdir("/opt/mysql") == False)):
        os.mkdir("/opt/mysql")
        os.chown("/opt/mysql", user[3], user[2])
        print "create dir /opt/mysql"

    if ((os.path.isdir("/opt/mysql/mysql-5.5.37-linux2.6-x86_64")) == False):
        os.chdir("/tmp")
        if (os.path.exists("daosen-mysql-5.5.37-linux2.6-x86_64.tar.gz") ==
                False):
            os.system(
                "wget http://192.168.199.75/mysql/daosen-mysql-5.5.37-linux2.6-x86_64.tar.gz -o /tmp/down.log"
            )
        print "Download Ok /tmp/daosen-mysql-5.5.37-linux2.6-x86_64.tar.gz"
        print "tar  zxf daosen-mysql-5.5.37-linux2.6-x86_64.tar.gz -C /opt/mysql"
        os.system(
            "tar zxf daosen-mysql-5.5.37-linux2.6-x86_64.tar.gz -C /opt/mysql")
        os.chown("/opt/mysql", user[3], user[2])
        print "create /opt/mysql/mysql-5.5.37-linux2.6-x86_64 ok!"

    if ((os.path.islink("/usr/local/mysql")) == False):
        os.symlink("/opt/mysql/mysql-5.5.37-linux2.6-x86_64",
                   "/usr/local/mysql")
        os.lchown("/usr/local/mysql", user[3], user[2])
        print "create link ok"

    if ((os.path.isdir("/data/mysql")) == False):
        os.mkdir("/data/mysql")
        os.chown("/data/mysql", user[3], user[2])
    cmd = "grep 'mysql' /etc/profile|grep -v grep|wc -l"
    mpNum = os.popen(cmd).read()
    if (int(mpNum) <= 0):
        print "export PATH=$PATH:/usr/local/mysql/bin >> /etc/profile"
        line = "export PATH=$PATH:/usr/local/mysql/bin"
        os.system("echo %s >>/etc/profile; source /etc/profile" % line)

    print "oscheck ok"
Example #60
0
def extract(pkgs_dir, dist):
    """
    Extract a package, i.e. make a package available for linkage.  We assume
    that the compressed packages is located in the packages directory.
    """
    with Locked(pkgs_dir):
        path = join(pkgs_dir, dist)
        t = tarfile.open(path + '.tar.bz2')
        t.extractall(path=path)
        t.close()
        if sys.platform.startswith('linux') and os.getuid() == 0:
            # When extracting as root, tarfile will by restore ownership
            # of extracted files.  However, we want root to be the owner
            # (our implementation of --no-same-owner).
            for root, dirs, files in os.walk(path):
                for fn in files:
                    p = join(root, fn)
                    os.lchown(p, 0, 0)