Python os.chmod() Examples

The following are 30 code examples of os.chmod(). 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: ssm.py    From aegea with Apache License 2.0 9 votes vote down vote up
def ensure_session_manager_plugin():
    session_manager_dir = os.path.join(config.user_config_dir, "bin")
    PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
    if shutil.which("session-manager-plugin", path=PATH):
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    else:
        os.makedirs(session_manager_dir, exist_ok=True)
        target_path = os.path.join(session_manager_dir, "session-manager-plugin")
        if platform.system() == "Darwin":
            download_session_manager_plugin_macos(target_path=target_path)
        elif platform.linux_distribution()[0] == "Ubuntu":
            download_session_manager_plugin_linux(target_path=target_path)
        else:
            download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
        os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    return shutil.which("session-manager-plugin", path=PATH) 
Example #2
Source File: test_tools.py    From delocate with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def test_ensure_writable():
    # Test ensure writable decorator
    with InTemporaryDirectory():
        with open('test.bin', 'wt') as fobj:
            fobj.write('A line\n')
        # Set to user rw, else r
        os.chmod('test.bin', 0o644)
        st = os.stat('test.bin')
        @ensure_writable
        def foo(fname):
            pass
        foo('test.bin')
        assert_equal(os.stat('test.bin'), st)
        # No-one can write
        os.chmod('test.bin', 0o444)
        st = os.stat('test.bin')
        foo('test.bin')
        assert_equal(os.stat('test.bin'), st) 
Example #3
Source File: test_utils.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def test_found_win32(self):
        sys.platform = 'win32'
        tempdir = os.environ['PATH'] = mkdtemp(self)
        os.environ['PATHEXT'] = pathsep.join(('.com', '.exe', '.bat'))
        f = join(tempdir, 'binary.exe')
        with open(f, 'w'):
            pass
        os.chmod(f, 0o777)
        self.assertEqual(which('binary'), f)
        self.assertEqual(which('binary.exe'), f)
        self.assertEqual(which(f), f)
        self.assertIsNone(which('binary.com'))

        os.environ['PATH'] = ''
        self.assertEqual(which('binary', path=tempdir), f)
        self.assertEqual(which('binary.exe', path=tempdir), f)
        self.assertEqual(which(f, path=tempdir), f)
        self.assertIsNone(which('binary.com', path=tempdir)) 
Example #4
Source File: examples.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def replace_gmsh():
    fn_gmsh = path2bin('gmsh')
    fn_gmsh_tmp = path2bin('gmsh_tmp')
    # move
    shutil.move(fn_gmsh, fn_gmsh_tmp)
    # replace
    if sys.platform == 'win32':
        fn_script = fn_gmsh[:4] + '.cmd'
        with open(fn_script, 'w') as f:
            f.write('echo "GMSH"')
    else:
        with open(fn_gmsh, 'w') as f:
            f.write('#! /bin/bash -e\n')
            f.write(f'"echo" "$@"')
        os.chmod(
            fn_gmsh,
            os.stat(fn_gmsh).st_mode |
            stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        )
    yield
    shutil.move(fn_gmsh_tmp, fn_gmsh) 
Example #5
Source File: tools.py    From delocate with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def ensure_permissions(mode_flags=stat.S_IWUSR):
    """decorator to ensure a filename has given permissions.

    If changed, original permissions are restored after the decorated
    modification.
    """

    def decorator(f):
        def modify(filename, *args, **kwargs):
            m = chmod_perms(filename) if exists(filename) else mode_flags
            if not m & mode_flags:
                os.chmod(filename, m | mode_flags)
            try:
                return f(filename, *args, **kwargs)
            finally:
                # restore original permissions
                if not m & mode_flags:
                    os.chmod(filename, m)
        return modify

    return decorator


# Open filename, checking for read permission 
Example #6
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copymode_local_to_local_symlink_dont_follow(tmpdir):
    test_dir = tmpdir.mkdir('test')
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    src_link = "%s\\source-link.txt" % test_dir
    dst_link = "%s\\target-link.txt" % test_dir

    os.symlink(src_filename, src_link)
    os.symlink(dst_filename, dst_link)

    expected = "chmod: follow_symlinks unavailable on this platform"
    with pytest.raises(NotImplementedError, match=re.escape(expected)):
        copymode(src_link, dst_link, follow_symlinks=False) 
Example #7
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copystat_local_to_local(tmpdir):
    test_dir = tmpdir.mkdir("test")
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)
    os.utime(src_filename, (1024, 1024))

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    copystat(src_filename, dst_filename)

    actual = os.stat(dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert stat.S_IMODE(actual.st_mode) & stat.S_IWRITE == 0 
Example #8
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copystat_local_to_local_symlink_dont_follow_fail(tmpdir):
    test_dir = tmpdir.mkdir('test')
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    src_link = "%s\\source-link.txt" % test_dir
    dst_link = "%s\\target-link.txt" % test_dir

    os.symlink(src_filename, src_link)
    os.symlink(dst_filename, dst_link)

    expected = "follow_symlinks unavailable on this platform"
    with pytest.raises(NotImplementedError, match=re.escape(expected)):
        copystat(src_link, dst_link, follow_symlinks=False) 
Example #9
Source File: shutil.py    From jawfish with MIT License 6 votes vote down vote up
def copymode(src, dst, *, follow_symlinks=True):
    """Copy mode bits from src to dst.

    If follow_symlinks is not set, symlinks aren't followed if and only
    if both `src` and `dst` are symlinks.  If `lchmod` isn't available
    (e.g. Linux) this method does nothing.

    """
    if not follow_symlinks and os.path.islink(src) and os.path.islink(dst):
        if hasattr(os, 'lchmod'):
            stat_func, chmod_func = os.lstat, os.lchmod
        else:
            return
    elif hasattr(os, 'chmod'):
        stat_func, chmod_func = os.stat, os.chmod
    else:
        return

    st = stat_func(src)
    chmod_func(dst, stat.S_IMODE(st.st_mode)) 
Example #10
Source File: test_regression.py    From gphotos-sync with MIT License 6 votes vote down vote up
def ___test_folder_not_writeable(self):
        # make sure we get permissions error and not 'database is locked'
        s = ts.SetupDbAndCredentials()
        s.test_setup("test_folder_not_writeable", trash_files=True, trash_db=True)
        try:
            if os.name == "nt":
                os.chmod(str(s.root), stat.S_IREAD)
            else:
                s.root.chmod(0o444)
            with self.assertRaises(PermissionError):
                s.gp.main([str(s.root), "--skip-shared-albums"])
        finally:
            if os.name == "nt":
                os.chmod(str(s.root), stat.S_IWRITE | stat.S_IREAD)
            else:
                os.chmod(str(s.root), 0o777)
            shutil.rmtree(str(s.root)) 
Example #11
Source File: generator_utils.py    From fine-lm with MIT License 6 votes vote down vote up
def gunzip_file(gz_path, new_path):
  """Unzips from gz_path into new_path.

  Args:
    gz_path: path to the zipped file.
    new_path: path to where the file will be unzipped.
  """
  if tf.gfile.Exists(new_path):
    tf.logging.info("File %s already exists, skipping unpacking" % new_path)
    return
  tf.logging.info("Unpacking %s to %s" % (gz_path, new_path))
  # We may be unpacking into a newly created directory, add write mode.
  mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH
  os.chmod(os.path.dirname(new_path), mode)
  with gzip.open(gz_path, "rb") as gz_file:
    with tf.gfile.GFile(new_path, mode="wb") as new_file:
      for line in gz_file:
        new_file.write(line) 
Example #12
Source File: filecache.py    From cutout with MIT License 6 votes vote down vote up
def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        filename = self._get_filename(key)
        self._prune()
        try:
            fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix,
                                       dir=self._path)
            f = os.fdopen(fd, 'wb')
            try:
                pickle.dump(int(time() + timeout), f, 1)
                pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
            finally:
                f.close()
            rename(tmp, filename)
            os.chmod(filename, self._mode)
        except (IOError, OSError):
            pass 
Example #13
Source File: mx_native.py    From mx with GNU General Public License v2.0 6 votes vote down vote up
def _run(self, *args, **kwargs):
        cmd = [self.binary, '-j', self.parallelism]
        if mx.get_opts().very_verbose:
            cmd += ['-v']
        cmd += args

        out = kwargs.get('out', mx.OutputCapture())
        err = kwargs.get('err', subprocess.STDOUT)
        if mx.get_opts().verbose:
            if callable(out) and '-n' not in args:
                out = mx.TeeOutputCapture(out)
            if callable(err):
                err = mx.TeeOutputCapture(err)

        try:
            rc = mx.run(cmd, nonZeroIsFatal=False, out=out, err=err, cwd=self.build_dir)
        except OSError as e:
            if e.errno != errno.EACCES:
                mx.abort('Error executing \'{}\': {}'.format(' '.join(cmd), str(e)))
            mx.logv('{} is not executable. Trying to change permissions...'.format(self.binary))
            os.chmod(self.binary, 0o755)
            self._run(*args, **kwargs)  # retry
        else:
            not rc or mx.abort(rc if mx.get_opts().verbose else out.data)  # pylint: disable=expression-not-assigned 
Example #14
Source File: config.py    From daily-wallpaper with MIT License 5 votes vote down vote up
def check(self):
        if not os.path.exists(CONFIG_FILE):
            if not os.path.exists(CONFIG_APP_DIR):
                os.makedirs(CONFIG_APP_DIR, 0o700)
            with open(CONFIG_FILE, 'a'):
                os.utime(CONFIG_FILE, None)
            os.chmod(CONFIG_FILE, 0o600) 
Example #15
Source File: paint.py    From unicorn-hat-hd with MIT License 5 votes vote down vote up
def save(filename):
    try:
        os.mkdir('saves/')
    except OSError:
        pass
    try:
        data = unicornhathd.get_pixels()
        data = repr(data)
        data = data.replace('array', 'list')
        print(filename, data)
        file = open('saves/' + filename + '.py', 'w')
        file.write("""#!/usr/bin/env python
import unicornhathd
import signal

unicornhathd.rotation(0)

pixels = {}

for x in range(unicornhathd.WIDTH):
    for y in range(unicornhathd.HEIGHT):
        r, g, b = pixels[x][y]
        unicornhathd.set_pixel(x, y, r, g, b)

unicornhathd.show()

print("\\nShowing: {}\\nPress Ctrl+C to exit!")

signal.pause()
""".format(data, filename))
        file.close()
        os.chmod('saves/' + filename + '.py', 0o777 | stat.S_IEXEC)

        return("ok" + str(unicornhathd.get_pixels()))
    except AttributeError:
        print("Unable to save, please update")
        print("unicornhathdhathd library!")
        return("fail") 
Example #16
Source File: extract.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def unzip(zip_file, output, stats, include_filter):
  """Unzips an archive using 'zipfile' python module.

  Works everywhere where Python works (Windows and POSIX).

  Args:
    zip_file: absolute path to an archive to unzip.
    output: existing directory to unzip to.
    stats: the stats dict (see main() for its form)
    include_filter (fn(path): bool): A function which is given the archive
      path and should return True if we should extract it.
  """
  with zipfile.ZipFile(zip_file) as zf:
    for zipinfo in zf.infolist():
      if not include_filter(zipinfo.filename):
        print 'Skipping %r (does not match include_files)' % (zipinfo.filename,)
        continue

      print 'Extracting %s' % zipinfo.filename
      stats['extracted']['filecount'] += 1
      stats['extracted']['bytes'] += zipinfo.file_size
      zf.extract(zipinfo, unc_path(output))

      if os.name != 'nt':
        # POSIX may store permissions in the 16 most significant bits of the
        # file's external attributes.
        perms = (zipinfo.external_attr >> 16) & 0o777
        if perms:
          fullpath = os.path.join(output, zipinfo.filename)
          # Don't update permissions to be more restrictive.
          old = os.stat(fullpath).st_mode
          old_short = old & 0o777
          new = old | perms
          new_short = new & 0o777
          if old_short < new_short:
            print 'Updating %s permissions (0%o -> 0%o)' % (
                zipinfo.filename, old_short, new_short)
            os.chmod(fullpath, new) 
Example #17
Source File: test_refactor.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def init_test_file(self, test_file):
        tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor")
        self.addCleanup(shutil.rmtree, tmpdir)
        shutil.copy(test_file, tmpdir)
        test_file = os.path.join(tmpdir, os.path.basename(test_file))
        os.chmod(test_file, 0o644)
        return test_file 
Example #18
Source File: bccache.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example #19
Source File: test_regression.py    From gphotos-sync with MIT License 5 votes vote down vote up
def test_zero_items_in_response(self, page_size):
        """
        for issue https://github.com/gilesknap/gphotos-sync/issues/112
        """
        # note this fails with page size below 5 and that might be another API
        # bug
        # to emulate issue #112 remove the date range and set page_size = 2
        # this then does download everything via media_items.list but sometimes
        # gets zero items with a next_page token (too expensive on quota to
        # always leave it like this.)
        page_size.return_value = 6

        s = ts.SetupDbAndCredentials()
        args = [
            "--skip-albums",
            "--index-only",
            "--start-date",
            "1965-01-01",
            "--end-date",
            "1965-12-31",
        ]
        s.test_setup(
            "test_zero_items_in_response", trash_files=True, trash_db=True, args=args
        )
        s.gp.start(s.parsed_args)

        db = LocalData(s.root)

        db.cur.execute("SELECT COUNT() FROM SyncFiles")
        count = db.cur.fetchone()
        self.assertEqual(10, count[0], "expected 10 images 1965")

    # this test does not work on windows - it does not throw an error so it
    # seems chmod fails to have an effect 
Example #20
Source File: install.py    From py-solc with MIT License 5 votes vote down vote up
def extract_release(identifier):
    release_zipfile_path = get_release_zipfile_path(identifier)

    extract_path = get_extract_path(identifier)
    ensure_path_exists(extract_path)

    print("Extracting zipfile: {0} -> {1}".format(release_zipfile_path, extract_path))

    with zipfile.ZipFile(release_zipfile_path) as zipfile_file:
        zipfile_file.extractall(extract_path)

    executable_path = get_executable_path(identifier)

    print("Making `solc` binary executable: `chmod +x {0}`".format(executable_path))
    chmod_plus_x(executable_path) 
Example #21
Source File: bccache.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example #22
Source File: postinstall_simnibs.py    From simnibs with GNU General Public License v3.0 5 votes vote down vote up
def _write_unix_sh(python_cli, bash_cli, commands='"$@"'):
    ''' Writes a bash script to evoke a python program '''
    print(f'Writing {bash_cli}')
    with open(bash_cli, 'w') as f:
        f.write('#! /bin/bash -e\n')
        f.write(f'"{sys.executable}" -E -u "{python_cli}" {commands}')
    os.chmod(bash_cli,
             os.stat(bash_cli).st_mode |
             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) 
Example #23
Source File: core_library.py    From toonapilib with MIT License 5 votes vote down vote up
def on_error(func, path, exc_info):  # pylint: disable=unused-argument
    """
    Error handler for ``shutil.rmtree``.

    If the error is due to an access error (read only file)
    it attempts to add write permission and then retries.

    If the error is for another reason it re-raises the error.

    Usage : ``shutil.rmtree(path, onerror=onerror)``

    # 2007/11/08
    # Version 0.2.6
    # pathutils.py
    # Functions useful for working with files and paths.
    # http://www.voidspace.org.uk/python/recipebook.shtml#utils

    # Copyright Michael Foord 2004
    # Released subject to the BSD License
    # Please see http://www.voidspace.org.uk/python/license.shtml

    # For information about bugfixes, updates and support, please join the Pythonutils mailing list.
    # http://groups.google.com/group/pythonutils/
    # Comments, suggestions and bug reports welcome.
    # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
    # E-mail fuzzyman@voidspace.org.uk
    """
    if not os.access(path, os.W_OK):
        # Is the error an access error ?
        os.chmod(path, stat.S_IWUSR)
        func(path)
    else:
        raise  # pylint: disable=misplaced-bare-raise 
Example #24
Source File: cli.py    From certidude with MIT License 5 votes vote down vote up
def make_runtime_dirs(func):
    def wrapped(**args):
        # systemd doesn't support RuntimeDirectoryPreserve=yes on Xenial
        # otherwise this should be part of service files
        # with RuntimeDirectory=certidude
        if not os.path.exists(const.RUN_DIR):
            click.echo("Creating: %s" % const.RUN_DIR)
            os.makedirs(const.RUN_DIR)
            os.chmod(const.RUN_DIR, 0o755)
        return func(**args)
    return wrapped 
Example #25
Source File: tarfile.py    From jawfish with MIT License 5 votes vote down vote up
def chmod(self, tarinfo, targetpath):
        """Set file permissions of targetpath according to tarinfo.
        """
        if hasattr(os, 'chmod'):
            try:
                os.chmod(targetpath, tarinfo.mode)
            except EnvironmentError as e:
                raise ExtractError("could not change mode") 
Example #26
Source File: widevine.py    From script.module.inputstreamhelper with MIT License 5 votes vote down vote up
def missing_widevine_libs():
    """Parses ldd output of libwidevinecdm.so and displays dialog if any depending libraries are missing."""
    if system_os() != 'Linux':  # this should only be needed for linux
        return None

    if cmd_exists('ldd'):
        widevinecdm = widevinecdm_path()
        if not os.access(widevinecdm, os.X_OK):
            log(0, 'Changing {path} permissions to 744.', path=widevinecdm)
            os.chmod(widevinecdm, 0o744)

        missing_libs = []
        cmd = ['ldd', widevinecdm]
        output = run_cmd(cmd, sudo=False)
        if output['success']:
            for line in output['output'].splitlines():
                if '=>' not in str(line):
                    continue
                lib_path = str(line).strip().split('=>')
                lib = lib_path[0].strip()
                path = lib_path[1].strip()
                if path == 'not found':
                    missing_libs.append(lib)

            if missing_libs:
                log(4, 'Widevine is missing the following libraries: {libs}', libs=missing_libs)
                return missing_libs

            log(0, 'There are no missing Widevine libraries! :-)')
            return None

    log(4, 'Failed to check for missing Widevine libraries.')
    return None 
Example #27
Source File: tarfile.py    From jawfish with MIT License 5 votes vote down vote up
def extractall(self, path=".", members=None):
        """Extract all members from the archive to the current working
           directory and set owner, modification time and permissions on
           directories afterwards. `path' specifies a different directory
           to extract to. `members' is optional and must be a subset of the
           list returned by getmembers().
        """
        directories = []

        if members is None:
            members = self

        for tarinfo in members:
            if tarinfo.isdir():
                # Extract directories with a safe mode.
                directories.append(tarinfo)
                tarinfo = copy.copy(tarinfo)
                tarinfo.mode = 0o700
            # Do not set_attrs directories, as we will do that further down
            self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())

        # Reverse sort directories.
        directories.sort(key=lambda a: a.name)
        directories.reverse()

        # Set correct owner, mtime and filemode on directories.
        for tarinfo in directories:
            dirpath = os.path.join(path, tarinfo.name)
            try:
                self.chown(tarinfo, dirpath)
                self.utime(tarinfo, dirpath)
                self.chmod(tarinfo, dirpath)
            except ExtractError as e:
                if self.errorlevel > 1:
                    raise
                else:
                    self._dbg(1, "tarfile: %s" % e) 
Example #28
Source File: test_config.py    From esmlab with Apache License 2.0 5 votes vote down vote up
def no_read_permissions(path):
    perm_orig = stat.S_IMODE(os.stat(path).st_mode)
    perm_new = perm_orig ^ stat.S_IREAD
    try:
        os.chmod(path, perm_new)
        yield
    finally:
        os.chmod(path, perm_orig) 
Example #29
Source File: server.py    From sanic with MIT License 5 votes vote down vote up
def bind_unix_socket(path: str, *, mode=0o666, backlog=100) -> socket.socket:
    """Create unix socket.
    :param path: filesystem path
    :param backlog: Maximum number of connections to queue
    :return: socket.socket object
    """
    """Open or atomically replace existing socket with zero downtime."""
    # Sanitise and pre-verify socket path
    path = os.path.abspath(path)
    folder = os.path.dirname(path)
    if not os.path.isdir(folder):
        raise FileNotFoundError(f"Socket folder does not exist: {folder}")
    try:
        if not stat.S_ISSOCK(os.stat(path, follow_symlinks=False).st_mode):
            raise FileExistsError(f"Existing file is not a socket: {path}")
    except FileNotFoundError:
        pass
    # Create new socket with a random temporary name
    tmp_path = f"{path}.{secrets.token_urlsafe()}"
    sock = socket.socket(socket.AF_UNIX)
    try:
        # Critical section begins (filename races)
        sock.bind(tmp_path)
        try:
            os.chmod(tmp_path, mode)
            # Start listening before rename to avoid connection failures
            sock.listen(backlog)
            os.rename(tmp_path, path)
        except:  # noqa: E722
            try:
                os.unlink(tmp_path)
            finally:
                raise
    except:  # noqa: E722
        try:
            sock.close()
        finally:
            raise
    return sock 
Example #30
Source File: zbx_alertlog.py    From zbxdb with GNU General Public License v3.0 5 votes vote down vote up
def check_log_files(sids):
    """ check existence and access"""

    for _sid, log_file in sids:
        # print("*{0}*".format(log_file))

        if not os.path.exists(log_file):
            # print("create \n{0}".format(log_file))
            open(log_file, 'a').close()
        # print("chmod")
        try:
            os.chmod(log_file, 0o744)
        except PermissionError:
            print("not allowed to chmod; run as owner")