Python stat.S_IRUSR Examples

The following are 30 code examples of stat.S_IRUSR(). 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 stat , 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: makebin.py    From pydarkstar with MIT License 7 votes vote down vote up
def chmod(path):
    os.chmod(path,
             # user
             stat.S_IRUSR |  # read
             stat.S_IWUSR |  # write
             stat.S_IXUSR |  # execute

             # group
             stat.S_IRGRP |  # read
             stat.S_IWGRP |  # write
             stat.S_IXGRP |  # execute

             # other
             stat.S_IROTH |  # read
             # stat.S_IWOTH | # write
             stat.S_IXOTH  # execute
             ) 
Example #3
Source File: test_import.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example #4
Source File: test_import.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example #5
Source File: test_test_support.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_rmtree(self):
        dirpath = support.TESTFN + 'd'
        subdirpath = os.path.join(dirpath, 'subdir')
        os.mkdir(dirpath)
        os.mkdir(subdirpath)
        support.rmtree(dirpath)
        self.assertFalse(os.path.exists(dirpath))
        with support.swap_attr(support, 'verbose', 0):
            support.rmtree(dirpath)

        os.mkdir(dirpath)
        os.mkdir(subdirpath)
        os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR)
        with support.swap_attr(support, 'verbose', 0):
            support.rmtree(dirpath)
        self.assertFalse(os.path.exists(dirpath))

        os.mkdir(dirpath)
        os.mkdir(subdirpath)
        os.chmod(dirpath, 0)
        with support.swap_attr(support, 'verbose', 0):
            support.rmtree(dirpath)
        self.assertFalse(os.path.exists(dirpath)) 
Example #6
Source File: test_file_system_helpers.py    From funfuzz with Mozilla Public License 2.0 6 votes vote down vote up
def test_rm_tree_incl_readonly_files(tmpdir):
    """Test that directory trees with readonly files can be removed.

    Args:
        tmpdir (class): Fixture from pytest for creating a temporary directory
    """
    test_dir = Path(tmpdir) / "test_dir"
    read_only_dir = test_dir / "nested_read_only_dir"
    read_only_dir.mkdir(parents=True)

    test_file = read_only_dir / "test.txt"
    with io.open(test_file, "w", encoding="utf-8", errors="replace") as f:
        f.write("testing\n")

    Path.chmod(test_file, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

    util.file_system_helpers.rm_tree_incl_readonly_files(test_dir) 
Example #7
Source File: test_import.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_execute_bit_not_copied(self):
        # Issue 6070: under posix .pyc files got their execute bit set if
        # the .py file had the execute bit set, but they aren't executable.
        oldmask = os.umask(022)
        sys.path.insert(0, os.curdir)
        try:
            fname = TESTFN + os.extsep + "py"
            f = open(fname, 'w').close()
            os.chmod(fname, (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
                             stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
            __import__(TESTFN)
            fn = fname + 'c'
            if not os.path.exists(fn):
                fn = fname + 'o'
                if not os.path.exists(fn):
                    self.fail("__import__ did not result in creation of "
                              "either a .pyc or .pyo file")
            s = os.stat(fn)
            self.assertEqual(stat.S_IMODE(s.st_mode),
                             stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        finally:
            os.umask(oldmask)
            remove_files(TESTFN)
            unload(TESTFN)
            del sys.path[0] 
Example #8
Source File: util.py    From octavia with Apache License 2.0 6 votes vote down vote up
def install_netns_systemd_service():
    os_utils = osutils.BaseOS.get_os_util()

    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    # mode 00644
    mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

    # TODO(bcafarel): implement this for other init systems
    # netns handling depends on a separate unit file
    netns_path = os.path.join(consts.SYSTEMD_DIR,
                              consts.AMP_NETNS_SVC_PREFIX + '.service')

    jinja_env = jinja2.Environment(
        autoescape=True, loader=jinja2.FileSystemLoader(os.path.dirname(
            os.path.realpath(__file__)
        ) + consts.AGENT_API_TEMPLATES))

    if not os.path.exists(netns_path):
        with os.fdopen(os.open(netns_path, flags, mode), 'w') as text_file:
            text = jinja_env.get_template(
                consts.AMP_NETNS_SVC_PREFIX + '.systemd.j2').render(
                    amphora_nsname=consts.AMPHORA_NAMESPACE,
                    HasIFUPAll=os_utils.has_ifup_all())
            text_file.write(text) 
Example #9
Source File: loadbalancer.py    From octavia with Apache License 2.0 6 votes vote down vote up
def upload_certificate(self, lb_id, filename):
        self._check_ssl_filename_format(filename)

        # create directory if not already there
        if not os.path.exists(self._cert_dir(lb_id)):
            os.makedirs(self._cert_dir(lb_id))

        stream = Wrapped(flask.request.stream)
        file = self._cert_file_path(lb_id, filename)
        flags = os.O_WRONLY | os.O_CREAT
        # mode 00600
        mode = stat.S_IRUSR | stat.S_IWUSR
        with os.fdopen(os.open(file, flags, mode), 'wb') as crt_file:
            b = stream.read(BUFFER)
            while b:
                crt_file.write(b)
                b = stream.read(BUFFER)

        resp = webob.Response(json=dict(message='OK'))
        resp.headers['ETag'] = stream.get_md5()
        return resp 
Example #10
Source File: launcher.py    From Computable with MIT License 6 votes vote down vote up
def write_batch_script(self, n):
        """Instantiate and write the batch script to the work_dir."""
        self.n = n
        # first priority is batch_template if set
        if self.batch_template_file and not self.batch_template:
            # second priority is batch_template_file
            with open(self.batch_template_file) as f:
                self.batch_template = f.read()
        if not self.batch_template:
            # third (last) priority is default_template
            self.batch_template = self.default_template
            # add jobarray or queue lines to user-specified template
            # note that this is *only* when user did not specify a template.
            self._insert_queue_in_script()
            self._insert_job_array_in_script()
        script_as_string = self.formatter.format(self.batch_template, **self.context)
        self.log.debug('Writing batch script: %s', self.batch_file)
        with open(self.batch_file, 'w') as f:
            f.write(script_as_string)
        os.chmod(self.batch_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) 
Example #11
Source File: ipcontrollerapp.py    From Computable with MIT License 6 votes vote down vote up
def save_connection_dict(self, fname, cdict):
        """save a connection dict to json file."""
        c = self.config
        url = cdict['registration']
        location = cdict['location']
        
        if not location:
            if PUBLIC_IPS:
                location = PUBLIC_IPS[-1]
            else:
                self.log.warn("Could not identify this machine's IP, assuming %s."
                " You may need to specify '--location=<external_ip_address>' to help"
                " IPython decide when to connect via loopback." % LOCALHOST)
                location = LOCALHOST
            cdict['location'] = location
        fname = os.path.join(self.profile_dir.security_dir, fname)
        self.log.info("writing connection info to %s", fname)
        with open(fname, 'w') as f:
            f.write(json.dumps(cdict, indent=2))
        os.chmod(fname, stat.S_IRUSR|stat.S_IWUSR) 
Example #12
Source File: test_dumbdbm.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_readonly_files(self):
        dir = _fname
        os.mkdir(dir)
        try:
            fname = os.path.join(dir, 'db')
            f = dumbdbm.open(fname, 'n')
            self.assertEqual(list(f.keys()), [])
            for key in self._dict:
                f[key] = self._dict[key]
            f.close()
            os.chmod(fname + ".dir", stat.S_IRUSR)
            os.chmod(fname + ".dat", stat.S_IRUSR)
            os.chmod(dir, stat.S_IRUSR|stat.S_IXUSR)
            f = dumbdbm.open(fname, 'r')
            self.assertEqual(sorted(f.keys()), sorted(self._dict))
            f.close()  # don't write
        finally:
            test_support.rmtree(dir) 
Example #13
Source File: server.py    From octavia with Apache License 2.0 6 votes vote down vote up
def upload_config(self):
        try:
            stream = flask.request.stream
            file_path = cfg.find_config_files(project=CONF.project,
                                              prog=CONF.prog)[0]
            flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
            # mode 00600
            mode = stat.S_IRUSR | stat.S_IWUSR
            with os.fdopen(os.open(file_path, flags, mode), 'wb') as cfg_file:
                b = stream.read(BUFFER)
                while b:
                    cfg_file.write(b)
                    b = stream.read(BUFFER)

            CONF.mutate_config_files()
        except Exception as e:
            LOG.error("Unable to update amphora-agent configuration: "
                      "{}".format(str(e)))
            return webob.Response(json=dict(
                message="Unable to update amphora-agent configuration.",
                details=str(e)), status=500)

        return webob.Response(json={'message': 'OK'}, status=202) 
Example #14
Source File: createmanifests.py    From binaryanalysis with Apache License 2.0 6 votes vote down vote up
def cleanupdir(temporarydir):
	osgen = os.walk(temporarydir)
	try:
		while True:
			i = osgen.next()
			## make sure all directories can be accessed
			for d in i[1]:
				if not os.path.islink(os.path.join(i[0], d)):
					os.chmod(os.path.join(i[0], d), stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
			for p in i[2]:
				try:
					if not os.path.islink(os.path.join(i[0], p)):
						os.chmod(os.path.join(i[0], p), stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
				except Exception, e:
					#print e
					pass
	except StopIteration:
		pass
	try:
		shutil.rmtree(temporarydir)
	except:
		## nothing that can be done right now, so just give up
		pass 
Example #15
Source File: sql.py    From wrds with MIT License 6 votes vote down vote up
def __create_pgpass_file_unix(self):
        """
        Create a .pgpass file on Unix-like operating systems.

        Permissions on this file must also be set on Unix-like systems.
        This function works on Mac OS X and Linux.
        It should work on Solaris too, but this is untested.
        """
        homedir = os.getenv('HOME')
        pgfile = homedir + os.path.sep + '.pgpass'
        if (os.path.isfile(pgfile)):
            # Set it to mode 600 (rw-------) so we can write to it
            os.chmod(pgfile, stat.S_IRUSR | stat.S_IWUSR)
        self.__write_pgpass_file(pgfile)
        # Set it to mode 400 (r------) to protect it
        os.chmod(pgfile, stat.S_IRUSR) 
Example #16
Source File: fwaudit.py    From fwaudit with GNU General Public License v2.0 6 votes vote down vote up
def get_sudo_user_group_mode():
    '''TBW'''
    # XXX only need uid, gid, and file mode for sudo case...
    new_uid = int(os.environ.get('SUDO_UID'))
    if new_uid is None:
        error('Unable to obtain SUDO_UID')
        return False
    #debug('new UID via SUDO_UID: ' + str(new_uid))
    new_gid = int(os.environ.get('SUDO_GID'))
    if new_gid is None:
        error('Unable to obtain SUDO_GID')
        return False
    #debug('new GID via SUDO_GID: ' + str(new_gid))
    # new_dir_mode = (stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IWGRP|stat.S_IROTH|stat.S_IWOTH)
    rwx_mode = (stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
    new_dir_mode = rwx_mode
    #debug('new dir mode: ' + str(new_dir_mode))
    return (new_dir_mode, new_uid, new_gid) 
Example #17
Source File: panel.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def _check_cert(filename):
    """
    Does this certificate file look okay?

    Returns error message, or None if okay
    """
    try:
        st = os.stat(filename)
    except OSError:
        return filename + " doesn't exist"
    else:
        good_perm = stat.S_IFREG | stat.S_IRUSR # | stat.S_IWUSR
        if (st[stat.ST_UID], st[stat.ST_GID]) != (0,0):
            return 'not owned by root.root'
        perm = st[stat.ST_MODE]
        if good_perm != perm:
            return "expected permissions %o but found %o." % (good_perm, perm) 
Example #18
Source File: lib.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def special_to_letter(mode):
    l = ''

    ALL_R = (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
    ALL_W = (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)

    if mode & stat.S_ISGID:
        l += 'G'
    if mode & stat.S_ISUID:
        l += 'U'
    if mode & stat.S_ISVTX:
        l += 'T'
    if mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
        l += 'E'
    if ( mode & ALL_R ) == ALL_R:
        l += 'R'
    if ( mode & ALL_W ) == ALL_W:
        l += 'W'

    return l 
Example #19
Source File: utilities.py    From passhport with GNU Affero General Public License v3.0 6 votes vote down vote up
def write_authorized_keys(name, sshkey):
    """Add the SSH key in authorize_keys with passhport call"""
    try:
        with open(config.SSH_KEY_FILE, "a", encoding="utf8") as \
                  authorized_keys_file:
                  authorized_keys_file.write('command="' + \
                                             config.PYTHON_PATH + \
                                             " " + config.PASSHPORT_PATH + \
                                             " " + name + '" ' + sshkey + "\n")
    except IOError:
        return response('ERROR: cannot write in the file ' + \
                        '"authorized_keys". However, the user is ' + \
                        'stored in the database.', 500)

    # set correct read/write permissions
    os.chmod(config.SSH_KEY_FILE, stat.S_IRUSR | stat.S_IWUSR)
    return True 
Example #20
Source File: dax_settings.py    From dax with MIT License 5 votes vote down vote up
def __init__(self):
        self.netrc_file = os.path.join(os.path.expanduser('~'), '.netrc')
        if not os.path.exists(self.netrc_file):
            open(self.netrc_file, 'a').close()
            # Setting mode for the file:
            os.chmod(self.netrc_file, stat.S_IWUSR | stat.S_IRUSR)
        self.is_secured()
        self.netrc_obj = netrc.netrc(self.netrc_file) 
Example #21
Source File: dax_tools_utils.py    From dax with MIT License 5 votes vote down vote up
def write(self):
        """Write config options to the ~/.dax_settings.ini file.

        :return: None
        """
        with open(self.settings_file, 'w+') as ini_f:
            ini_f.write(INI_HEADER)
            self.config_parser.write(ini_f)
        os.chmod(self.settings_file, stat.S_IWUSR | stat.S_IRUSR) 
Example #22
Source File: utils.py    From pipenv with MIT License 5 votes vote down vote up
def set_write_bit(fn):
    if isinstance(fn, six.string_types) and not os.path.exists(fn):
        return
    os.chmod(fn, stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR)
    return 
Example #23
Source File: _script.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _create_listening_directory(self, directory_path):
        """
        Create the parent directory for the Unix socket if it doesn't exist.

        :param FilePath directory_path: The directory to create.
        """
        original_umask = umask(0)
        try:
            if not directory_path.exists():
                directory_path.makedirs()
            directory_path.chmod(S_IRUSR | S_IWUSR | S_IXUSR)
        finally:
            umask(original_umask) 
Example #24
Source File: keychain.py    From bdbag with Apache License 2.0 5 votes vote down vote up
def write_keychain(keychain=DEFAULT_KEYCHAIN, keychain_file=DEFAULT_KEYCHAIN_FILE):
    keychain_path = os.path.dirname(keychain_file)
    if not os.path.isdir(keychain_path):
        try:
            os.makedirs(keychain_path)
        except OSError as error:  # pragma: no cover
            if error.errno != errno.EEXIST:
                raise
    with open(keychain_file, 'w') as kf:
        kf.write(json.dumps(keychain if keychain is not None else list(),
                            sort_keys=True, indent=4, separators=(',', ': ')))
    os.chmod(keychain_file, stat.S_IRUSR | stat.S_IWUSR) 
Example #25
Source File: util.py    From Computable with MIT License 5 votes vote down vote up
def generate_exec_key(keyfile):
    import uuid
    newkey = str(uuid.uuid4())
    with open(keyfile, 'w') as f:
        # f.write('ipython-key ')
        f.write(newkey+'\n')
    # set user-only RW permissions (0600)
    # this will have no effect on Windows
    os.chmod(keyfile, stat.S_IRUSR|stat.S_IWUSR) 
Example #26
Source File: piku.py    From piku with MIT License 5 votes vote down vote up
def setup_authorized_keys(ssh_fingerprint, script_path, pubkey):
    """Sets up an authorized_keys file to redirect SSH commands"""

    authorized_keys = join(environ['HOME'], '.ssh', 'authorized_keys')
    if not exists(dirname(authorized_keys)):
        makedirs(dirname(authorized_keys))
    # Restrict features and force all SSH commands to go through our script
    with open(authorized_keys, 'a') as h:
        h.write("""command="FINGERPRINT={ssh_fingerprint:s} NAME=default {script_path:s} $SSH_ORIGINAL_COMMAND",no-agent-forwarding,no-user-rc,no-X11-forwarding,no-port-forwarding {pubkey:s}\n""".format(**locals()))
    chmod(dirname(authorized_keys), S_IRUSR | S_IWUSR | S_IXUSR)
    chmod(authorized_keys, S_IRUSR | S_IWUSR) 
Example #27
Source File: lib.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def make_readonly(path: str):
    """Make a file read-only."""
    assert os.path.isfile(path)
    os.chmod(path, stat.S_IROTH | stat.S_IRUSR | stat.S_IRGRP) 
Example #28
Source File: iso.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def set_iso_permissions(self):
        """Set permissions to 644"""
        mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
        os.chmod(self.get_path(), mode) 
Example #29
Source File: wikize_refs.py    From betterscientificsoftware.github.io with MIT License 5 votes vote down vote up
def write_output_file(outlines, in_filename, out_filename, no_readonly):
    outfname = out_filename
    if not out_filename:
        outfname = "%s-wikized.md"%os.path.splitext(in_filename)[0]
    with open(outfname, 'w') as outf:
        outf.writelines(["%s" % line for line in outlines])
    if not no_readonly:
        os.chmod(outfname, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH) 
Example #30
Source File: base.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def _writeJSON(data, file_name):
        """Parse and writes the JSON VM config file."""
        json_data = json.dumps(data, indent=2, separators=(',', ': '))

        # Open the config file and write to contents
        config_file = open(file_name, 'w')
        config_file.write(json_data)
        config_file.close()

        # Check file permissions, only giving read/write access to root
        os.chmod(file_name, stat.S_IWUSR | stat.S_IRUSR)
        os.chown(file_name, 0, 0)