Python stat.S_IRWXG Examples

The following are 30 code examples for showing how to use stat.S_IRWXG(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module stat , or try the search function .

Example 1
Project: gazee   Author: hubbcaps   File: comicscan.py    License: GNU General Public License v3.0 6 votes vote down vote up
def build_unpack_comic(self, comic_path):
        logging.info("%s unpack requested" % comic_path)
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, "build"), topdown=False):
            for f in files:
                os.chmod(os.path.join(root, f), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.remove(os.path.join(root, f))
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, "build"), topdown=False):
            for d in dirs:
                os.chmod(os.path.join(root, d), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.rmdir(os.path.join(root, d))
        if comic_path.endswith(".cbr"):
            opened_rar = rarfile.RarFile(comic_path)
            opened_rar.extractall(os.path.join(gazee.TEMP_DIR, "build"))
        elif comic_path.endswith(".cbz"):
            opened_zip = zipfile.ZipFile(comic_path)
            opened_zip.extractall(os.path.join(gazee.TEMP_DIR, "build"))
        return 
Example 2
Project: gazee   Author: hubbcaps   File: comicscan.py    License: GNU General Public License v3.0 6 votes vote down vote up
def user_unpack_comic(self, comic_path, user):
        logging.info("%s unpack requested" % comic_path)
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, user), topdown=False):
            for f in files:
                os.chmod(os.path.join(root, f), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.remove(os.path.join(root, f))
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, user), topdown=False):
            for d in dirs:
                os.chmod(os.path.join(root, d), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.rmdir(os.path.join(root, d))
        if comic_path.endswith(".cbr"):
            opened_rar = rarfile.RarFile(comic_path)
            opened_rar.extractall(os.path.join(gazee.TEMP_DIR, user))
        elif comic_path.endswith(".cbz"):
            opened_zip = zipfile.ZipFile(comic_path)
            opened_zip.extractall(os.path.join(gazee.TEMP_DIR, user))
        return

    # This method will return a list of .jpg files in their numberical order to be fed into the reading view. 
Example 3
Project: pytest-sftpserver   Author: ulope   File: interface.py    License: MIT License 6 votes vote down vote up
def stat(self):
        if self.content_provider.get(self.path) is None:
            return SFTP_NO_SUCH_FILE

        mtime = calendar.timegm(datetime.now().timetuple())

        sftp_attrs = SFTPAttributes()
        sftp_attrs.st_size = self.content_provider.get_size(self.path)
        sftp_attrs.st_uid = 0
        sftp_attrs.st_gid = 0
        sftp_attrs.st_mode = (
            stat.S_IRWXO
            | stat.S_IRWXG
            | stat.S_IRWXU
            | (stat.S_IFDIR if self.content_provider.is_dir(self.path) else stat.S_IFREG)
        )
        sftp_attrs.st_atime = mtime
        sftp_attrs.st_mtime = mtime
        sftp_attrs.filename = posixpath.basename(self.path)
        return sftp_attrs 
Example 4
Project: st2   Author: StackStorm   File: actions.py    License: Apache License 2.0 6 votes vote down vote up
def _write_data_file(self, pack_ref, file_path, content):
        """
        Write data file on disk.
        """
        # Throw if pack directory doesn't exist
        pack_base_path = get_pack_base_path(pack_name=pack_ref)
        if not os.path.isdir(pack_base_path):
            raise ValueError('Directory for pack "%s" doesn\'t exist' % (pack_ref))

        # Create pack sub-directory tree if it doesn't exist
        directory = os.path.dirname(file_path)

        if not os.path.isdir(directory):
            # NOTE: We apply same permission bits as we do on pack install. If we don't do that,
            # st2api won't be able to write to pack sub-directory
            mode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH
            os.makedirs(directory, mode)

        with open(file_path, 'w') as fp:
            fp.write(content) 
Example 5
Project: nano-dpow   Author: guilhermelawless   File: socket.py    License: MIT License 6 votes vote down vote up
def get_socket(path: str):
    # Adapted from https://github.com/aio-libs/aiohttp/issues/4155#issuecomment-539640591
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        if stat.S_ISSOCK(os.stat(path).st_mode):
            os.remove(path)
    except FileNotFoundError:
        pass

    try:
        sock.bind(path)
    except OSError as exc:
        sock.close()
        if exc.errno == errno.EADDRINUSE:
            msg = f'Address {path!r} is already in use'
            raise OSError(errno.EADDRINUSE, msg) from None
        else:
            raise
    except:
        sock.close()
        raise

    os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH)
    return sock 
Example 6
Project: backintime   Author: bit-team   File: password_ipc.py    License: GNU General Public License v2.0 6 votes vote down vote up
def isFifo(self):
        """
        make sure file is still a FIFO and has correct permissions
        """
        try:
            s = os.stat(self.fifo)
        except OSError:
            return False
        if not s.st_uid == os.getuid():
            logger.error('%s is not owned by user' % self.fifo, self)
            return False
        mode = s.st_mode
        if not stat.S_ISFIFO(mode):
            logger.error('%s is not a FIFO' % self.fifo, self)
            return False
        forbidden_perm = stat.S_IXUSR + stat.S_IRWXG + stat.S_IRWXO
        if mode & forbidden_perm > 0:
            logger.error('%s has wrong permissions' % self.fifo, self)
            return False
        return True 
Example 7
Project: black   Author: psf   File: lib.py    License: MIT License 6 votes vote down vote up
def handle_PermissionError(
    func: Callable, path: Path, exc: Tuple[Any, Any, Any]
) -> None:
    """
    Handle PermissionError during shutil.rmtree.

    This checks if the erroring function is either 'os.rmdir' or 'os.unlink', and that
    the error was EACCES (i.e. Permission denied). If true, the path is set writable,
    readable, and executable by everyone. Finally, it tries the error causing delete
    operation again.

    If the check is false, then the original error will be reraised as this function
    can't handle it.
    """
    excvalue = exc[1]
    LOG.debug(f"Handling {excvalue} from {func.__name__}... ")
    if func in (os.rmdir, os.unlink) and excvalue.errno == errno.EACCES:
        LOG.debug(f"Setting {path} writable, readable, and executable by everyone... ")
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # chmod 0777
        func(path)  # Try the error causing delete operation again
    else:
        raise 
Example 8
Project: code   Author: grawity   File: netrc.py    License: MIT License 6 votes vote down vote up
def check_owner(fp):
    if os.name != 'posix':
        return
    prop = os.fstat(fp.fileno())
    if prop.st_uid != os.getuid():
        import pwd
        try:
            fowner = pwd.getpwuid(prop.st_uid)[0]
        except KeyError:
            fowner = 'uid %s' % prop.st_uid
        try:
            user = pwd.getpwuid(os.getuid())[0]
        except KeyError:
            user = 'uid %s' % os.getuid()
        raise NetrcParseError(
            ("~/.netrc file owner (%s) does not match"
             " current user (%s)") % (fowner, user),
            file, lexer.lineno)
    if prop.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
        raise NetrcParseError(
           "~/.netrc access too permissive: access"
           " permissions must restrict access to only"
           " the owner", file, lexer.lineno) 
Example 9
Project: CGATPipelines   Author: CGATOxford   File: Cluster.py    License: MIT License 6 votes vote down vote up
def setDrmaaJobPaths(job_template, job_path):
    '''Adds the job_path, stdout_path and stderr_paths
       to the job_template.
    '''
    job_path = os.path.abspath(job_path)

    os.chmod(job_path, stat.S_IRWXG | stat.S_IRWXU)

    stdout_path = job_path + ".stdout"
    stderr_path = job_path + ".stderr"

    job_template.remoteCommand = job_path
    job_template.outputPath = ":" + stdout_path
    job_template.errorPath = ":" + stderr_path

    return job_template, stdout_path, stderr_path 
Example 10
Project: jawfish   Author: war-and-code   File: regrtest.py    License: MIT License 5 votes vote down vote up
def cleanup_test_droppings(testname, verbose):
    import shutil
    import stat
    import gc

    # First kill any dangling references to open files etc.
    # This can also issue some ResourceWarnings which would otherwise get
    # triggered during the following test run, and possibly produce failures.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print("%r left behind %s %r" % (testname, kind, name))
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception as msg:
            print(("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)), file=sys.stderr) 
Example 11
Project: openeo-python-client   Author: Open-EO   File: oidc.py    License: Apache License 2.0 5 votes vote down vote up
def _get_all(self, empty_on_file_not_found=True) -> dict:
        if not self._path.exists():
            if empty_on_file_not_found:
                return {}
            raise FileNotFoundError(self._path)
        mode = self._path.stat().st_mode
        if (mode & stat.S_IRWXG) or (mode & stat.S_IRWXO):
            raise PermissionError(
                "Refresh token file {p} is readable by others: st_mode {a:o} (expected permissions: {e:o}).".format(
                    p=self._path, a=mode, e=self._PERMS)
            )
        with self._path.open("r", encoding="utf8") as f:
            log.info("Using refresh tokens from {p}".format(p=self._path))
            return json.load(f) 
Example 12
Project: ironpython2   Author: IronLanguages   File: regrtest.py    License: Apache License 2.0 5 votes vote down vote up
def cleanup_test_droppings(testname, verbose):
    import stat
    import gc

    # First kill any dangling references to open files etc.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print "%r left behind %s %r" % (testname, kind, name)
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception, msg:
            print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)) 
Example 13
Project: ironpython2   Author: IronLanguages   File: test_stat.py    License: Apache License 2.0 5 votes vote down vote up
def test_mode(self):
        with open(TESTFN, 'w'):
            pass
        if os.name == 'posix':
            os.chmod(TESTFN, 0o700)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXU)

            os.chmod(TESTFN, 0o070)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXG)

            os.chmod(TESTFN, 0o007)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXO)

            os.chmod(TESTFN, 0o444)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode), 0o444)
        else:
            os.chmod(TESTFN, 0o700)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IFMT(st_mode),
                             stat.S_IFREG) 
Example 14
Project: spore   Author: wiremas   File: run_unit_test.py    License: MIT License 5 votes vote down vote up
def remove_read_only(func, path, exc):
    """ Called by shutil.rmtree when it encounters a readonly file. """
    excvalue = exc[1]
    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
        os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
        func(path)
    else:
        raise RuntimeError('Could not remove {0}'.format(path)) 
Example 15
Project: gpkit   Author: convexengineering   File: mosek_cli.py    License: MIT License 5 votes vote down vote up
def remove_read_only(func, path, exc):
    "If we can't remove a file/directory, change permissions and try again."
    if func in (os.rmdir, os.remove) and exc[1].errno == errno.EACCES:
        # change the file to be readable,writable,executable: 0777
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
        func(path)  # try again 
Example 16
Project: edgedb   Author: edgedb   File: pgconnparams.py    License: Apache License 2.0 5 votes vote down vote up
def _read_password_file(passfile: pathlib.Path) -> List[Tuple[str, ...]]:

    passtab = []

    try:
        if not passfile.exists():
            return []

        if not passfile.is_file():
            warnings.warn(
                'password file {!r} is not a plain file'.format(passfile))

            return []

        if _system != 'Windows':
            if passfile.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
                warnings.warn(
                    'password file {!r} has group or world access; '
                    'permissions should be u=rw (0600) or less'.format(
                        passfile))

                return []

        with passfile.open('rt') as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#'):
                    # Skip empty lines and comments.
                    continue
                # Backslash escapes both itself and the colon,
                # which is a record separator.
                line = line.replace(R'\\', '\n')
                passtab.append(tuple(
                    p.replace('\n', R'\\')
                    for p in re.split(r'(?<!\\):', line, maxsplit=4)
                ))
    except IOError:
        pass

    return passtab 
Example 17
Project: BinderFilter   Author: dxwu   File: regrtest.py    License: MIT License 5 votes vote down vote up
def cleanup_test_droppings(testname, verbose):
    import stat
    import gc

    # First kill any dangling references to open files etc.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (test_support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print "%r left behind %s %r" % (testname, kind, name)
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception, msg:
            print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)) 
Example 18
Project: batch-shipyard   Author: Azure   File: crypto.py    License: MIT License 5 votes vote down vote up
def check_ssh_private_key_filemode(ssh_private_key):
    # type: (pathlib.Path) -> bool
    """Check SSH private key filemode
    :param pathlib.Path ssh_private_key: SSH private key
    :rtype: bool
    :return: private key filemode is ok
    """
    def _mode_check(fstat, flag):
        return bool(fstat & flag)
    if util.on_windows():
        return True
    fstat = ssh_private_key.stat().st_mode
    modes = frozenset((stat.S_IRWXG, stat.S_IRWXO))
    return not any([_mode_check(fstat, x) for x in modes]) 
Example 19
Project: oss-ftp   Author: aliyun   File: regrtest.py    License: MIT License 5 votes vote down vote up
def cleanup_test_droppings(testname, verbose):
    import stat
    import gc

    # First kill any dangling references to open files etc.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (test_support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print "%r left behind %s %r" % (testname, kind, name)
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception, msg:
            print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)) 
Example 20
Project: oss-ftp   Author: aliyun   File: test_stat.py    License: MIT License 5 votes vote down vote up
def test_mode(self):
        with open(TESTFN, 'w'):
            pass
        if os.name == 'posix':
            os.chmod(TESTFN, 0o700)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXU)

            os.chmod(TESTFN, 0o070)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXG)

            os.chmod(TESTFN, 0o007)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode),
                             stat.S_IRWXO)

            os.chmod(TESTFN, 0o444)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IMODE(st_mode), 0o444)
        else:
            os.chmod(TESTFN, 0o700)
            st_mode = self.get_mode()
            self.assertS_IS("REG", st_mode)
            self.assertEqual(stat.S_IFMT(st_mode),
                             stat.S_IFREG) 
Example 21
Project: pythonfinder   Author: sarugaku   File: testutils.py    License: MIT License 5 votes vote down vote up
def set_write_bit(fn):
    # type: (str) -> None
    """
    Set read-write permissions for the current user on the target path.  Fail silently
    if the path doesn't exist.

    :param str fn: The target filename or path
    :return: None
    """

    if not os.path.exists(fn):
        return
    file_stat = os.stat(fn).st_mode
    os.chmod(fn, file_stat | stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
    if not os.path.isdir(fn):
        for path in [fn, os.path.dirname(fn)]:
            try:
                os.chflags(path, 0)
            except AttributeError:
                pass
        return None
    for root, dirs, files in os.walk(fn, topdown=False):
        for dir_ in [os.path.join(root, d) for d in dirs]:
            set_write_bit(dir_)
        for file_ in [os.path.join(root, f) for f in files]:
            set_write_bit(file_) 
Example 22
Project: Safejumper-for-Desktop   Author: proxysh   File: test_adbapi.py    License: GNU General Public License v2.0 5 votes vote down vote up
def startDB(self):
        import kinterbasdb
        self.DB_NAME = os.path.join(self.DB_DIR, DBTestConnector.DB_NAME)
        os.chmod(self.DB_DIR, stat.S_IRWXU + stat.S_IRWXG + stat.S_IRWXO)
        sql = 'create database "%s" user "%s" password "%s"'
        sql %= (self.DB_NAME, self.DB_USER, self.DB_PASS);
        conn = kinterbasdb.create_database(sql)
        conn.close() 
Example 23
Project: deepWordBug   Author: QData   File: fileoperations.py    License: Apache License 2.0 5 votes vote down vote up
def set_all_unrestricted_permissions(location):
    """
    Set permissions so that user, group, and others all have read,
    write and execute permissions (chmod 777).
    :param location: Full location of either a folder or a location
    """
    os.chmod(location, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) 
Example 24
Project: dax   Author: VUIIS   File: dax_settings.py    License: MIT License 5 votes vote down vote up
def is_secured(self):
        """ Check if file is secure."""
        st = os.stat(self.netrc_file)
        grp_access = bool(st.st_mode & stat.S_IRWXG)
        other_access = bool(st.st_mode & stat.S_IRWXO)
        if grp_access or other_access:
            msg = 'Wrong permission on %s file. Only you should have read and \
write access.'
            raise DaxNetrcError(msg % self.netrc_file) 
Example 25
Project: flocker   Author: ClusterHQ   File: service.py    License: Apache License 2.0 5 votes vote down vote up
def _make_public(self, filesystem):
        """
        Make a filesystem publically readable/writeable/executable.

        A better alternative will be implemented in
        https://clusterhq.atlassian.net/browse/FLOC-34

        :param filesystem: A ``IFilesystem`` provider.
        """
        filesystem.get_path().chmod(
            # 0o777 the long way:
            stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) 
Example 26
Project: flocker   Author: ClusterHQ   File: blockdevice.py    License: Apache License 2.0 5 votes vote down vote up
def run(self, deployer, state_persister):
        """
        Run the system ``mount`` tool to mount this change's volume's block
        device.  The volume must be attached to this node.
        """
        # Create the directory where a device will be mounted.
        # The directory's parent's permissions will be set to only allow access
        # by owner, to limit access by other users on the node.
        try:
            self.mountpoint.makedirs()
        except OSError as e:
            if e.errno != EEXIST:
                return fail()
        self.mountpoint.parent().chmod(S_IRWXU)

        # This should be asynchronous.  FLOC-1797
        deployer.block_device_manager.mount(self.device_path, self.mountpoint)

        # Remove lost+found to ensure filesystems always start out empty.
        # Mounted filesystem is also made world
        # writeable/readable/executable since we can't predict what user a
        # container will run as.  We make sure we change mounted
        # filesystem's root directory permissions, so we only do this
        # after the filesystem is mounted.  If other files exist we don't
        # bother with either change, since at that point user has modified
        # the volume and we don't want to undo their changes by mistake
        # (e.g. postgres doesn't like world-writeable directories once
        # it's initialized).

        # A better way is described in
        # https://clusterhq.atlassian.net/browse/FLOC-2074
        lostfound = self.mountpoint.child(b"lost+found")
        if self.mountpoint.children() == [lostfound]:
            lostfound.remove()
            self.mountpoint.chmod(S_IRWXU | S_IRWXG | S_IRWXO)
            self.mountpoint.restat()

        return succeed(None) 
Example 27
Project: mock-ssh-server   Author: carletes   File: test_sftp.py    License: MIT License 5 votes vote down vote up
def test_chmod(sftp_client, tmp_dir):
    test_file = os.path.join(tmp_dir, "foo")
    open(test_file, "w").write("X")
    sftp_client.chmod(test_file, 0o600)
    st = os.stat(test_file)
    check_bits = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO
    assert st.st_mode & check_bits == 0o600 
Example 28
Project: glance_store   Author: openstack   File: filesystem.py    License: Apache License 2.0 5 votes vote down vote up
def _set_exec_permission(self, datadir):
        """
        Set the execution permission of owner-group and/or other-users to
        image directory if the image file which contained needs relevant
        access permissions.

        :datadir is a directory path in which glance writes image files.
        """

        if self.backend_group:
            fstore_perm = getattr(
                self.conf, self.backend_group).filesystem_store_file_perm
        else:
            fstore_perm = self.conf.glance_store.filesystem_store_file_perm

        if fstore_perm <= 0:
            return

        try:
            mode = os.stat(datadir)[stat.ST_MODE]
            perm = int(str(fstore_perm), 8)
            if perm & stat.S_IRWXO > 0:
                if not mode & stat.S_IXOTH:
                    # chmod o+x
                    mode |= stat.S_IXOTH
                    os.chmod(datadir, mode)
            if perm & stat.S_IRWXG > 0:
                if not mode & stat.S_IXGRP:
                    # chmod g+x
                    os.chmod(datadir, mode | stat.S_IXGRP)
        except (IOError, OSError):
            LOG.warning(_LW("Unable to set execution permission of "
                            "owner-group and/or other-users to datadir: %s")
                        % datadir) 
Example 29
Project: Fluid-Designer   Author: Microvellum   File: regrtest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cleanup_test_droppings(testname, verbose):
    import shutil
    import stat
    import gc

    # First kill any dangling references to open files etc.
    # This can also issue some ResourceWarnings which would otherwise get
    # triggered during the following test run, and possibly produce failures.
    gc.collect()

    # Try to clean up junk commonly left behind.  While tests shouldn't leave
    # any files or directories behind, when a test fails that can be tedious
    # for it to arrange.  The consequences can be especially nasty on Windows,
    # since if a test leaves a file open, it cannot be deleted by name (while
    # there's nothing we can do about that here either, we can display the
    # name of the offending test, which is a real help).
    for name in (support.TESTFN,
                 "db_home",
                ):
        if not os.path.exists(name):
            continue

        if os.path.isdir(name):
            kind, nuker = "directory", shutil.rmtree
        elif os.path.isfile(name):
            kind, nuker = "file", os.unlink
        else:
            raise SystemError("os.path says %r exists but is neither "
                              "directory nor file" % name)

        if verbose:
            print("%r left behind %s %r" % (testname, kind, name))
        try:
            # if we have chmod, fix possible permissions problems
            # that might prevent cleanup
            if (hasattr(os, 'chmod')):
                os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            nuker(name)
        except Exception as msg:
            print(("%r left behind %s %r and it couldn't be "
                "removed: %s" % (testname, kind, name, msg)), file=sys.stderr) 
Example 30
Project: abstar   Author: briney   File: basemount.py    License: MIT License 5 votes vote down vote up
def copy_fastqs(self, destination_dir, show_progress=True):
        make_dir(destination_dir)
        if show_progress:
            start = datetime.now()
            progress_bar(0, self.num_fastqs, start_time=start)
        for i, fastq_file in enumerate(self.fastqs, 1):
            shutil.copy(fastq_file, destination_dir)
            dest_file = os.path.join(destination_dir, os.path.basename(fastq_file))
            try:
                os.chmod(dest_file, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            except PermissionError:
                continue
            if show_progress:
                is_complete = i == self.num_fastqs
                progress_bar(i, self.num_fastqs, start_time=start, complete=is_complete)