Python os.fchmod() Examples

The following are 30 code examples of os.fchmod(). 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: snapshots.py    From backintime with GNU General Public License v2.0 6 votes vote down vote up
def flockExclusive(self):
        """
        Block :py:func:`backup` from other profiles or users
        and run them serialized
        """
        if self.config.globalFlock():
            logger.debug('Set flock %s' %self.GLOBAL_FLOCK, self)
            self.flock = open(self.GLOBAL_FLOCK, 'w')
            fcntl.flock(self.flock, fcntl.LOCK_EX)
            #make it rw by all if that's not already done.
            perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | \
                    stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH
            s = os.fstat(self.flock.fileno())
            if not s.st_mode & perms == perms:
                logger.debug('Set flock permissions %s' %self.GLOBAL_FLOCK, self)
                os.fchmod(self.flock.fileno(), perms) 
Example #2
Source File: target.py    From mitogen with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_file_mode(path, spec, fd=None):
    """
    Update the permissions of a file using the same syntax as chmod(1).
    """
    if isinstance(spec, int):
        new_mode = spec
    elif not mitogen.core.PY3 and isinstance(spec, long):
        new_mode = spec
    elif spec.isdigit():
        new_mode = int(spec, 8)
    else:
        mode = os.stat(path).st_mode
        new_mode = apply_mode_spec(spec, mode)

    if fd is not None and hasattr(os, 'fchmod'):
        os.fchmod(fd, new_mode)
    else:
        os.chmod(path, new_mode) 
Example #3
Source File: gui_button.py    From traffic with MIT License 6 votes vote down vote up
def make_app(self):
        icon_path = ICON_PATH / "travel-white.svg"
        script_path = os.path.expanduser("~/.local/bin/traffic_gui.sh")

        with open(script_path, "w") as fh:
            fh.write(self.linux_script.format(python_exe=sys.executable))
            mode = os.fstat(fh.fileno()).st_mode
            mode |= 0o111
            os.fchmod(fh.fileno(), mode & 0o7777)

        with open("traffic.desktop", "w") as fh:
            fh.write(
                self.linux_desktop.format(
                    icon_path=icon_path, script_path=script_path
                )
            )
            mode = os.fstat(fh.fileno()).st_mode
            mode |= 0o111
            os.fchmod(fh.fileno(), mode & 0o7777)

        subprocess.call(
            "desktop-file-install --dir ~/.local/share/applications "
            "traffic.desktop --rebuild-mime-info-cache",
            shell=True,
        ) 
Example #4
Source File: server.py    From python with Apache License 2.0 6 votes vote down vote up
def server_bind(self):
        """Called by constructor to bind the socket.

        May be overridden.

        """
        if self.allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setblocking(True)

        if not self.listen_fd:
            self.socket.bind(self.server_address)

        self.server_address = self.socket.getsockname()

        if self.server_address[0] == 0:
            self.server_address = '@' + self.server_address[1:].decode('utf-8')
            if self.mode:
                os.fchmod(self.socket.fileno(), mode=int(self.mode, 8))
        elif self.mode:
            os.chmod(self.server_address, mode=int(self.mode, 8)) 
Example #5
Source File: generator.py    From ops-cli with Apache License 2.0 6 votes vote down vote up
def generate(self, dest, config):
        plugins = {
            plugin.__name__: plugin for plugin in self.inventory_plugins}
        plugin = plugins[config.get('plugin')]

        inventory_json = plugin(config.get('args', {}))

        script_content = self.template.format(
            config=repr(config),
            plugin_path=plugin.__module__,
            json_content=inventory_json
        )
        script_dest = "%s/%s-%s.sh" % (dest, self.cluster_name, uuid.uuid4())

        with open(script_dest, 'w+') as f:
            f.write(script_content)
            os.fchmod(f.fileno(), 0o500) 
Example #6
Source File: _utils.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def script_write(filename, script):
    """Write a script to a file.

    Proper execute permissions will be set.

    :param ``str`` filename:
        File to write to.
    :param ``iterable|unicode`` script:
        Unicode string or iterable.
    """
    if isinstance(script, six.string_types):
        # If the script is fully provided in a string, wrap it in a StringIO
        if hasattr(script, 'decode'):
            script = io.StringIO(script.decode())
        else:
            script = io.StringIO(script)

    def _chunks_write(f):
        for chunk in script:
            f.write(chunk)
        if os.name == 'posix':
            f.write('\n\n')
            os.fchmod(f.fileno(), 0o755)

    _write(filename, _chunks_write, mode='w', permission=0o755) 
Example #7
Source File: utils.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def write_data(fpath, data, modified, raise_err=True, tmp_dir=None):
    """Safely write data to file path.
    """
    tmp_dir = tmp_dir or os.path.dirname(fpath)
    with tempfile.NamedTemporaryFile(dir=tmp_dir,
                                     delete=False,
                                     prefix='.tmp') as temp:
        if data:
            temp.write(data)
        if os.name == 'posix':
            os.fchmod(temp.fileno(), 0o644)
    os.utime(temp.name, (modified, modified))
    try:
        os.rename(temp.name, fpath)
    except OSError:
        _LOGGER.error('Unable to rename: %s => %s', temp.name, fpath,
                      exc_info=True)
        if raise_err:
            raise 
Example #8
Source File: configuration.py    From airflow with Apache License 2.0 6 votes vote down vote up
def tmp_configuration_copy(chmod=0o600):
    """
    Returns a path for a temporary file including a full copy of the configuration
    settings.
    :return: a path to a temporary file
    """
    cfg_dict = conf.as_dict(display_sensitive=True, raw=True)
    temp_fd, cfg_path = mkstemp()

    with os.fdopen(temp_fd, 'w') as temp_file:
        # Set the permissions before we write anything to it.
        if chmod is not None:
            os.fchmod(temp_fd, chmod)
        json.dump(cfg_dict, temp_file)

    return cfg_path 
Example #9
Source File: fix_dropbox.py    From dropbox_ext4 with MIT License 6 votes vote down vote up
def main():
    # Install the library.
    os.makedirs(os.path.join(INSTALL_PATH, 'lib'), exist_ok=True)

    with open(LIBRARY_PATH, 'wb') as fd:
        fd.write(gzip.decompress(base64.b85decode(ENCODED_LIB_CONTENTS)))
        os.fchmod(fd.fileno(), 0o755)

    # Install the wrapper script.
    os.makedirs(os.path.join(INSTALL_PATH, 'bin'), exist_ok=True)

    with open(SCRIPT_PATH, 'w') as fd:
        fd.write(DROPBOX_WRAPPER_CONTENTS)
        os.fchmod(fd.fileno(), 0o755)

    print("Installed the library and the wrapper script at:\n  %s\n  %s" % (LIBRARY_PATH, SCRIPT_PATH))
    print("(To uninstall, simply delete them.)")

    # Check that the correct 'dropbox' is in the $PATH.
    result = subprocess.check_output(['which', 'dropbox']).decode().rstrip()
    if result != SCRIPT_PATH:
        print()
        print("You will need to fix your $PATH! Currently, %r takes precedence." % result) 
Example #10
Source File: encgen.py    From custodia with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, config, section):
        super(EncryptedOverlay, self).__init__(config, section)
        self.store_name = self.backing_store
        self.store = None
        self.protected_header = None

        if (not os.path.isfile(self.master_key)
                and self.autogen_master_key):
            # XXX https://github.com/latchset/jwcrypto/issues/50
            size = self.key_sizes.get(self.master_enctype, 512)
            key = JWK(generate='oct', size=size)
            with open(self.master_key, 'w') as f:
                os.fchmod(f.fileno(), 0o600)
                f.write(key.export())

        with open(self.master_key) as f:
            data = f.read()
            key = json_decode(data)
            self.mkey = JWK(**key) 
Example #11
Source File: guiplex.py    From epoptes with GNU General Public License v3.0 6 votes vote down vote up
def client_command(self, handle, command):
        """Remotely called from uiconnection.py->Daemon.command."""
        if handle not in exchange.known_clients:
            LOG.e("Unknown client %s, can't execute %s" % (handle, command))
            # raise ValueError("Unknown client")
            return {'filename': '', 'result': b''}

        dfr = exchange.known_clients[handle].command(command)

        def send_result(result):
            """Callback for bashplex.py->DelimitedBashReceiver.command."""
            if len(result) < 65000:
                return {'filename': '', 'result': result}
            tmpf = tempfile.NamedTemporaryFile('wb', dir="/run/epoptes",
                                               delete=False)
            tmpf.write(result)
            os.fchmod(tmpf.file.fileno(), 0o660)
            return {'filename': tmpf.name, 'result': b''}

        dfr.addCallback(send_result)
        return dfr 
Example #12
Source File: setup.py    From kamene with GNU General Public License v2.0 6 votes vote down vote up
def make_ezipfile(base_name, base_dir, verbose=0, dry_run=0, **kwargs):
    fname = archive_util.make_zipfile(base_name, base_dir, verbose, dry_run)
    ofname = fname+".old"
    os.rename(fname,ofname)
    of=open(ofname)
    f=open(fname,"w")
    f.write(EZIP_HEADER % base_dir)
    while True:
        data = of.read(8192)
        if not data:
            break
        f.write(data)
    f.close()
    os.system("zip -A '%s'" % fname)
    of.close()
    os.unlink(ofname)
    os.fchmod(fname,0o755)
    return fname 
Example #13
Source File: bubble.py    From chopsticks with Apache License 2.0 6 votes vote down vote up
def handle_begin_put(req_id, path, mode):
    prev_umask = os.umask(0o077)
    try:
        if path is None:
            f = tempfile.NamedTemporaryFile(delete=False)
            path = wpath = f.name
        else:
            path = force_str(path)
            if os.path.isdir(path):
                raise IOError('%s is a directory' % path)
            wpath = path + '~chopsticks-tmp'
            f = open(wpath, 'wb')
    finally:
        os.umask(prev_umask)
    os.fchmod(f.fileno(), mode)
    active_puts[req_id] = (f, wpath, path, sha1()) 
Example #14
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_fchmod(self):
        self.check(os.fchmod, 0) 
Example #15
Source File: __init__.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def copy(self, dst, src=None):
        """Atomically copy tickets to destination."""
        if src is None:
            src = self.tkt_path

        dst_dir = os.path.dirname(dst)
        with io.open(src, 'rb') as tkt_src_file:
            # TODO; rewrite as fs.write_safe.
            with tempfile.NamedTemporaryFile(dir=dst_dir,
                                             prefix='.tmp' + self.princ,
                                             delete=False,
                                             mode='wb') as tkt_dst_file:
                try:
                    # Copy binary from source to dest
                    shutil.copyfileobj(tkt_src_file, tkt_dst_file)
                    # Set the owner
                    if self.uid is not None:
                        os.fchown(tkt_dst_file.fileno(), self.uid, -1)
                    # Copy the mode
                    src_stat = os.fstat(tkt_src_file.fileno())
                    os.fchmod(tkt_dst_file.fileno(),
                              stat.S_IMODE(src_stat.st_mode))
                    tkt_dst_file.flush()
                    os.rename(tkt_dst_file.name, dst)

                except (IOError, OSError):
                    _LOGGER.exception('Error copying ticket from %s to %s',
                                      src, dst)
                finally:
                    fs.rm_safe(tkt_dst_file.name) 
Example #16
Source File: common.py    From pghoard with Apache License 2.0 5 votes vote down vote up
def create_pgpass_file(connection_string_or_info):
    """Look up password from the given object which can be a dict or a
    string and write a possible password in a pgpass file;
    returns a connection_string without a password in it"""
    info = pgutil.get_connection_info(connection_string_or_info)
    if "password" not in info:
        return pgutil.create_connection_string(info)
    linekey = "{host}:{port}:{dbname}:{user}:".format(
        host=info.get("host", "localhost"),
        port=info.get("port", 5432),
        user=info.get("user", ""),
        dbname=info.get("dbname", "*"))
    pwline = "{linekey}{password}".format(linekey=linekey, password=info.pop("password"))
    pgpass_path = os.path.join(os.environ.get("HOME"), ".pgpass")
    if os.path.exists(pgpass_path):
        with open(pgpass_path, "r") as fp:
            pgpass_lines = fp.read().splitlines()
    else:
        pgpass_lines = []
    if pwline in pgpass_lines:
        LOG.debug("Not adding authentication data to: %s since it's already there", pgpass_path)
    else:
        # filter out any existing lines with our linekey and add the new line
        pgpass_lines = [line for line in pgpass_lines if not line.startswith(linekey)] + [pwline]
        content = "\n".join(pgpass_lines) + "\n"
        with open(pgpass_path, "w") as fp:
            os.fchmod(fp.fileno(), 0o600)
            fp.write(content)
        LOG.debug("Wrote %r to %r", pwline, pgpass_path)
    return pgutil.create_connection_string(info) 
Example #17
Source File: generate_oauth2_credentials.py    From hyou with Apache License 2.0 5 votes vote down vote up
def main(argv):
    parser = create_parser()
    opts = parser.parse_args(argv[1:])

    flow = oauth2client.client.OAuth2WebServerFlow(
        client_id=opts.client_id,
        client_secret=opts.client_secret,
        scope=hyou.SCOPES)
    url = flow.step1_get_authorize_url('urn:ietf:wg:oauth:2.0:oob')

    print()
    print('Please visit this URL to get the authorization code:')
    print(url)
    print()

    code = py3.input('Code: ').strip()

    credentials = flow.step2_exchange(code)

    with py3.open(opts.output_json_path, 'wb') as f:
        os.fchmod(f.fileno(), 0o600)
        f.write(
            py3.native_str_to_bytes(credentials.to_json(), encoding='utf-8'))

    print()
    print('Credentials successfully saved to %s' % opts.output_json_path)
    print()
    print('WARNING: Keep it in a safe location! With the credentials,')
    print('         all your Google Drive documents can be accessed.') 
Example #18
Source File: file_utils.py    From conary with Apache License 2.0 5 votes vote down vote up
def fchmod(fobj, mode):
    os.fchmod(_fileno(fobj), mode) 
Example #19
Source File: setup.py    From squadron with MIT License 5 votes vote down vote up
def setup(etcdir, vardir):
    """ Prompts the user if necessary to set up directories """
    is_root = os.geteuid() == 0
    default_etc = {
            True: '/etc/squadron',
            False: os.path.join(os.path.expanduser('~'),'.squadron')
        }
    default_var = {
            True: '/var/squadron',
            False: os.path.join(os.path.expanduser('~'),'.squadron', 'state')
        }

    if not etcdir:
        result = raw_input("Location for config [{}]: ".format(default_etc[is_root]))
        etcdir = result if result else default_etc[is_root]

    if not vardir:
        result = raw_input("Location for state [{}]: ".format(default_var[is_root]))
        vardir = result if result else default_var[is_root]

    ret = init_system(etcdir, vardir)

    if is_root:
        result = raw_input("Install init script? [N/y] ")
        if result == "Y" or result == "y":
            init_script = resource_string(__name__,
                    os.path.join('init', 'init-script-ubuntu'))
            with open('/etc/init.d/squadron', 'w') as init_file:
                init_file.write(init_script.format(vardir))
                os.fchmod(init_file.fileno(),
                         stat.S_IRWXU |  stat.S_IRGRP | stat.S_IROTH)

    return ret 
Example #20
Source File: mitogen-fuse.py    From mitogen with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _create(path, mode):
    fd = os.open(path, os.O_WRONLY)
    try:
        os.fchmod(fd, mode)
    finally:
        os.close(fd) 
Example #21
Source File: monitor.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def execute(self, data):
        """Put the container into the down state which will trigger cleanup.
        """
        _LOGGER.critical('Container down: %r', data)

        unique_name, service_name = data['id'].split(',')
        container_dir = os.path.join(self._tm_env.apps_dir, unique_name)
        container_svc = supervisor.open_service(container_dir)
        data_dir = container_svc.data_dir

        exitinfo_file = os.path.join(os.path.join(data_dir, EXIT_INFO))
        try:
            with io.open(exitinfo_file, 'x') as f:
                _LOGGER.info('Creating exitinfo file: %s', exitinfo_file)
                if os.name == 'posix':
                    os.fchmod(f.fileno(), 0o644)
                f.writelines(
                    utils.json_genencode({
                        'service': service_name,
                        'return_code': data['return_code'],
                        'signal': data['signal'],
                        'timestamp': data['timestamp']
                    })
                )
        except FileExistsError as err:
            _LOGGER.info('exitinfo file already exists: %s', exitinfo_file)

        try:
            supervisor.control_service(container_svc.directory,
                                       supervisor.ServiceControlAction.down)
        except subproc.CalledProcessError as err:
            _LOGGER.warning('Failed to bring down container: %s', unique_name)

        return True 
Example #22
Source File: test_os.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fchmod(self):
        self.check(os.fchmod, 0) 
Example #23
Source File: kernel_watchdog.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def start(self):
        """Start watchdog."""
        _LOGGER.info('Setting up kernel watchdog at %s', self.root)

        # set up clean base directory
        fs.rmtree_safe(self.root)
        fs.mkdir_safe(self.root)
        fs.mkdir_safe(self.script_directory)
        fs.mkdir_safe(self.test_directory)

        # set up configuration
        config = _JINJA2_ENV.get_template(
            'kernel-watchdog-conf'
        ).render(
            test_directory=self.test_directory
        )
        with io.open(self.config_file, 'w') as fd:
            fd.write(config)

        # set up custom tests
        for name in self.tests:
            test_script = os.path.join(self.script_directory, name)
            # test script
            with io.open(test_script, 'w') as fd:
                fd.write(self.tests[name])
                os.fchmod(fd.fileno(), 0o755)
            # custom test
            custom_test = _JINJA2_ENV.get_template(
                'kernel-watchdog-test'
            ).render(
                name=name,
                command=test_script,
            )
            with io.open(os.path.join(self.test_directory, name), 'w') as fd:
                fd.write(custom_test)
                os.fchmod(fd.fileno(), 0o755)

        _LOGGER.info('Starting up kernel watchdog (ncpu=%d)', self.cpu_count)
        os.environ['WATCHDOGD_NCPU'] = str(self.cpu_count)
        subproc.exec_fghack(self.start_command) 
Example #24
Source File: __init__.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def create_script(filename, templatename, mode=_EXEC_MODE, **kwargs):
    """This Creates a file from a JINJA template.

    The templates exist in our lib/python/treadmill/templates directory.

    :param ``str`` filename:
        Name of the file to generate.
    :param ``str`` templatename:
        The name of the template file.
    :param ``int`` mode:
        The mode for the file (Defaults to +x).
    :param ``dict`` kwargs:
        key/value passed into the template.
    """
    jinja_env = jinja2.Environment(loader=jinja2.PackageLoader('treadmill'))

    filepath = os.path.dirname(filename)
    with tempfile.NamedTemporaryFile(dir=filepath,
                                     delete=False,
                                     mode='w') as f:
        data = jinja_env.get_template(templatename).render(**kwargs)
        f.write(data)
        if os.name == 'posix':
            # cast to int required in order for default _EXEC_MODE to work
            os.fchmod(f.fileno(), int(mode))

    if sys.version_info[0] < 3:
        # TODO: os.rename cannot replace on windows
        # (use os.replace in python 3.4)
        # copied from fs as utils cannot have this dependency
        if os.name == 'nt':
            win32api.MoveFileEx(f.name, filename,
                                win32con.MOVEFILE_REPLACE_EXISTING)
        else:
            os.rename(f.name, filename)
    else:
        os.replace(f.name, filename) 
Example #25
Source File: iptables.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def _temp_dump_file(data):
    """dump rule,ipset into a temp file
    """
    with tempfile.NamedTemporaryFile(delete=False, mode='w') as f:
        f.write(data)
        os.fchmod(f.fileno(), 0o644)
        return f.name 
Example #26
Source File: test_os.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_fchmod(self):
        if hasattr(os, "fchmod"):
            self.check(os.fchmod, 0) 
Example #27
Source File: _exxo_importer.py    From exxo with ISC License 5 votes vote down vote up
def _extract_so_file(self, src, dst):
        with self.exe_zip.open(src) as src:
            with open(dst, 'wb') as dst:
                shutil.copyfileobj(src, dst)
                os.fchmod(dst.fileno(), 0o700) 
Example #28
Source File: test_os.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_fchmod(self):
        if hasattr(os, "fchmod"):
            self.check(os.fchmod, 0) 
Example #29
Source File: installer.py    From dials with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def install_precommitbx_hook(path, python):
    with path.join(".git", "hooks", "pre-commit").open("w") as fh:
        fh.write(precommitbx_template(python))
        mode = os.fstat(fh.fileno()).st_mode
        mode |= stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        os.fchmod(fh.fileno(), stat.S_IMODE(mode)) 
Example #30
Source File: ptempfile.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def mkstemp(*args, **kwargs):
    """Wrap tempfile.mkstemp, setting the permissions of the created temporary
    file as specified in settings (see bug 1983).
    """
    fd, name = tempfile.mkstemp(*args, **kwargs)
    if hasattr(os, "fchmod"):
        os.fchmod(fd, settings.ZING_SYNC_FILE_MODE)
    else:
        os.chmod(name, settings.ZING_SYNC_FILE_MODE)
    return fd, name