Python stat.S_IROTH Examples

The following are 30 code examples of stat.S_IROTH(). 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: 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 #2
Source File: generator_utils.py    From training_results_v0.5 with Apache License 2.0 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 #3
Source File: generator_utils.py    From tensor2tensor with Apache License 2.0 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 #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: utils_disk.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def close(self):
        error_context.context(
            "Creating unattended install CD image %s" % self.path)
        if os.path.exists(os.path.join(self.mount, 'isolinux')):
            # bootable cdrom
            f = open(os.path.join(self.mount, 'isolinux', 'isolinux.cfg'), 'w')
            f.write('default /isolinux/vmlinuz append initrd=/isolinux/'
                    'initrd.img %s\n' % self.extra_params)
            f.close()
            boot = '-b isolinux/isolinux.bin'
        else:
            # Not a bootable CDROM, using -kernel instead (eg.: arm64)
            boot = ''

        m_cmd = ('mkisofs -o %s %s -c isolinux/boot.cat -no-emul-boot '
                 '-boot-load-size 4 -boot-info-table -f -R -J -V -T %s'
                 % (self.path, boot, self.mount))
        process.run(m_cmd)
        os.chmod(self.path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP |
                 stat.S_IROTH | stat.S_IXOTH)
        cleanup(self.mount)
        cleanup(self.source_cdrom)
        logging.debug("unattended install CD image %s successfully created",
                      self.path) 
Example #6
Source File: container_analyze.py    From MalAnalyzer with GNU General Public License v3.0 6 votes vote down vote up
def start_trace(self):
        try:
            os.chmod(self.mal_path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)  # mode:744
            self.logger.debug('Chmod %s to %s successfully.' % (self.mal_path, '744'))

            trace_path = os.path.join(self.result_path, '%s.txt' % self.tracemode)

            ltrace_cmd = ['ltrace', '-f', '-ttt', '-S', '-o', trace_path, self.mal_path]
            strace_cmd = ["strace", "-ttt", "-x", "-y", "-yy", "-s", "32", "-o", trace_path, "-f", self.mal_path]

            trace_cmd = ltrace_cmd if self.tracemode == 'ltrace' else strace_cmd
            child = subprocess.Popen(trace_cmd)
            self.logger.debug(trace_cmd)
            if child.poll() is None:
                self.logger.info("Start %s(pid=%s) successfully." % (self.tracemode, child.pid))
                self.progrunner = self.tracemode
                setattr(self,self.tracemode,child)
            else:
                self.logger.error("Start %s failed." % self.tracemode)
                sys.exit()
        except Exception, e:
            self.logger.exception('%s: %s' % (Exception, e))
            sys.exit()

    ### 
Example #7
Source File: PreferencesVarietyDialog.py    From variety with GNU General Public License v3.0 6 votes vote down vote up
def on_copyto_changed(self):
        self.ui.copyto_faq_link.set_sensitive(self.ui.copyto_enabled.get_active())
        if self.ui.copyto_enabled.get_active() and self.copyto_chooser.get_folder():
            folder = self.copyto_chooser.get_folder()
            self.ui.copyto_use_default.set_sensitive(
                folder != self.parent.get_actual_copyto_folder("Default")
            )
            under_encrypted = Util.is_home_encrypted() and folder.startswith(
                os.path.expanduser("~") + "/"
            )
            self.ui.copyto_encrypted_note.set_visible(under_encrypted)
            can_write = os.access(self.parent.get_actual_copyto_folder(folder), os.W_OK)
            can_read = os.stat(folder).st_mode | stat.S_IROTH
            self.ui.copyto_faq_link.set_visible(can_write and can_read and not under_encrypted)
            self.ui.copyto_permissions_box.set_visible(not can_write or not can_read)
            self.ui.copyto_write_permissions_warning.set_visible(not can_write)
            self.ui.copyto_read_permissions_warning.set_visible(not can_read)
        else:
            self.ui.copyto_faq_link.set_visible(True)
            self.ui.copyto_encrypted_note.set_visible(False)
            self.ui.copyto_permissions_box.set_visible(False)
        self.delayed_apply() 
Example #8
Source File: PreferencesVarietyDialog.py    From variety with GNU General Public License v3.0 6 votes vote down vote up
def on_copyto_fix_permissions_clicked(self, widget=None):
        folder = self.copyto_chooser.get_folder()
        can_write = os.access(self.parent.get_actual_copyto_folder(folder), os.W_OK)
        can_read = os.stat(folder).st_mode | stat.S_IROTH
        mode = "a+"
        if not can_read:
            mode += "r"
        if not can_write:
            mode += "w"
        try:
            Util.superuser_exec("chmod", mode, folder)
        except Exception:
            logger.exception(lambda: "Could not adjust copyto folder permissions")
            self.parent.show_notification(
                _("Could not adjust permissions"),
                _('You may try manually running this command:\nsudo chmod %s "%s"')
                % (mode, folder),
            )
        self.on_copyto_changed() 
Example #9
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 #10
Source File: plots.py    From TextDetector with GNU General Public License v3.0 6 votes vote down vote up
def make_readable(fn):
    """
    Make a file readable by all.
    Practical when the plot is in your public_html.


    Parameters
    ----------
    fn : str
        Filename you wish to make public readable.
    """

    st = os.stat(fn)

    # Create the desired permission
    st_mode = st.st_mode
    read_all = stat.S_IRUSR
    read_all |= stat.S_IRGRP
    read_all |= stat.S_IROTH

    # Set the permission
    os.chmod(fn, st_mode | read_all) 
Example #11
Source File: test_import.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #12
Source File: data_dir.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def get_tmp_dir(public=True):
    """
    Get the most appropriate tmp dir location.

    :param public: If public for all users' access
    """
    persistent_dir = settings.get_value('vt.common', 'tmp_dir',
                                        default="")
    if persistent_dir != "":
        return persistent_dir
    tmp_dir = None
    # apparmor deny /tmp/* /var/tmp/* and cause failure across tests
    # it is better to handle here
    if distro.detect().name == 'Ubuntu':
        tmp_dir = "/var/lib/libvirt/images"
        if not utils_path.usable_rw_dir(tmp_dir):
            logging.warning("Unable to write in '/var/lib/libvirt/images' "
                            "on Ubuntu, apparmor might complain...")
            tmp_dir = None
    tmp_dir = data_dir.get_tmp_dir(basedir=tmp_dir)
    if public:
        tmp_dir_st = os.stat(tmp_dir)
        os.chmod(tmp_dir, tmp_dir_st.st_mode | stat.S_IXUSR |
                 stat.S_IXGRP | stat.S_IXOTH | stat.S_IRGRP | stat.S_IROTH)
    return tmp_dir 
Example #13
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 #14
Source File: test_file_loader.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_read_only_bytecode(self):
        # When bytecode is read-only but should be rewritten, fail silently.
        with source_util.create_modules('_temp') as mapping:
            # Create bytecode that will need to be re-created.
            py_compile.compile(mapping['_temp'])
            bytecode_path = self.util.cache_from_source(mapping['_temp'])
            with open(bytecode_path, 'r+b') as bytecode_file:
                bytecode_file.seek(0)
                bytecode_file.write(b'\x00\x00\x00\x00')
            # Make the bytecode read-only.
            os.chmod(bytecode_path,
                        stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
            try:
                # Should not raise OSError!
                self.import_(mapping['_temp'], '_temp')
            finally:
                # Make writable for eventual clean-up.
                os.chmod(bytecode_path, stat.S_IWUSR) 
Example #15
Source File: directory.py    From king-phisher-plugins with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render_python_value(value):
		if not isinstance(value, int):
			return
		if value & stat.S_IFDIR:
			perm = 'd'
		else:
			perm = '-'
		perm += 'r' if value & stat.S_IRUSR else '-'
		perm += 'w' if value & stat.S_IWUSR else '-'
		if value & stat.S_ISUID:
			perm += 's' if value & stat.S_IXUSR else 'S'
		else:
			perm += 'x' if value & stat.S_IXUSR else '-'

		perm += 'r' if value & stat.S_IRGRP else '-'
		perm += 'w' if value & stat.S_IWGRP else '-'
		if value & stat.S_ISGID:
			perm += 's' if value & stat.S_IXGRP else 'S'
		else:
			perm += 'x' if value & stat.S_IXGRP else '-'

		perm += 'r' if value & stat.S_IROTH else '-'
		perm += 'w' if value & stat.S_IWOTH else '-'
		perm += 'x' if value & stat.S_IXOTH else '-'
		return perm 
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: injector.py    From pylane with GNU General Public License v3.0 6 votes vote down vote up
def ensure_code_file(self, code, file_path):
        """"""
        if file_path:
            file_path = os.path.abspath(file_path)
            if not os.path.isfile(file_path):
                raise RequirementsInvalid(
                    'Arg file_path is not a valid file.'
                )
            self.code_file = file_path
        else:
            if code:
                (fd, temp_file_path) = tempfile.mkstemp()
                with os.fdopen(fd, 'w') as f:
                    f.write(code)
                self.code_file = self.temp_file = temp_file_path
            else:
                raise RequirementsInvalid(
                    'Neither code nor code file_path specified.'
                )
        st = os.stat(self.code_file)
        os.chmod(self.code_file,
                 st.st_mode | stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) 
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: 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 #20
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 #21
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 #22
Source File: test_file_loader.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_read_only_bytecode(self):
        # When bytecode is read-only but should be rewritten, fail silently.
        with util.create_modules('_temp') as mapping:
            # Create bytecode that will need to be re-created.
            py_compile.compile(mapping['_temp'])
            bytecode_path = self.util.cache_from_source(mapping['_temp'])
            with open(bytecode_path, 'r+b') as bytecode_file:
                bytecode_file.seek(0)
                bytecode_file.write(b'\x00\x00\x00\x00')
            # Make the bytecode read-only.
            os.chmod(bytecode_path,
                        stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
            try:
                # Should not raise OSError!
                self.import_(mapping['_temp'], '_temp')
            finally:
                # Make writable for eventual clean-up.
                os.chmod(bytecode_path, stat.S_IWUSR) 
Example #23
Source File: find_circ.py    From find_circ with GNU General Public License v3.0 6 votes vote down vote up
def store_index(self,ipath):
        debug("# indexed_fasta.store_index('%s')" % ipath)
        
        # write to tmp-file first and in the end rename in order to have this atomic 
        # otherwise parallel building of the same index may screw it up.
        
        import tempfile
        tmp = tempfile.NamedTemporaryFile(mode="w",dir = os.path.dirname(ipath),delete=False)
        for chrom in sorted(self.chrom_stats.keys()):
            ofs,ldata,skip,skipchar,size = self.chrom_stats[chrom]
            tmp.write("%s\t%d\t%d\t%d\t%r\t%d\n" % (chrom,ofs,ldata,skip,skipchar,size))
        
        # make sure everything is on disk
        os.fsync(tmp)
        tmp.close()
        
        # make it accessible to everyone
        import stat
        os.chmod(tmp.name, stat.S_IROTH | stat.S_IRGRP | stat.S_IRUSR)
        
        # this is atomic on POSIX as we have created tmp in the same directory, 
        # therefore same filesystem
        os.rename(tmp.name,ipath) 
Example #24
Source File: generator_utils.py    From BERT with Apache License 2.0 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 #25
Source File: osutils.py    From octavia with Apache License 2.0 6 votes vote down vote up
def write_port_interface_file(self, netns_interface, fixed_ips, mtu,
                                  interface_file_path, template_port):
        # write interface file

        # If we are using a consolidated interfaces file, just append
        # otherwise clear the per interface file as we are rewriting it
        # TODO(johnsom): We need a way to clean out old interfaces records
        if CONF.amphora_agent.agent_server_network_file:
            flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
        else:
            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

        with os.fdopen(os.open(interface_file_path, flags, mode),
                       'w') as text_file:
            text = self._generate_network_file_text(
                netns_interface, fixed_ips, mtu, template_port)
            text_file.write(text) 
Example #26
Source File: file.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def check_permissions(cls, libvirt_config, directory):
        """Check permissions of directory and attempt to fix
        if libvirt user does not have permissions to read/write
        """
        require_permissions_if_owned = (
            stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR |
            stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
        )
        required_permissions_global = (
            stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH
        )
        libvirt_user_uid = pwd.getpwnam(libvirt_config.LIBVIRT_USER).pw_uid
        libvirt_group_gid = grp.getgrnam(libvirt_config.LIBVIRT_GROUP).gr_gid
        stat_info = os.stat(directory)

        # Check owner and group of directory
        if ((stat_info.st_uid != libvirt_user_uid or
             stat_info.st_gid != libvirt_group_gid or not
             # Check that libvirt has RWX (user and group)
             (stat_info.st_mode & require_permissions_if_owned ==
              require_permissions_if_owned)) and not
                # Otherwise, Check if 'other' has RWX
                (stat_info.st_mode & required_permissions_global ==
                 required_permissions_global)):

            # User/group are not those required for libvirt and permissions
            # of directory is not 777
            # Attempt to change directory owner/group
            os.chown(directory, libvirt_user_uid, libvirt_group_gid)
            # Append the required permissions to the current permissions
            os.chmod(directory, stat_info.st_mode | require_permissions_if_owned) 
Example #27
Source File: generate_download_script.py    From exoplanet-ml with Apache License 2.0 5 votes vote down vote up
def main(argv):
  del argv  # Unused.

  # Read Kepler targets.
  kepids = set()
  with open(FLAGS.kepler_csv_file) as f:
    reader = csv.DictReader(row for row in f if not row.startswith("#"))
    for row in reader:
      kepids.add(row["kepid"])

  num_kepids = len(kepids)

  # Write wget commands to script file.
  with open(FLAGS.output_file, "w") as f:
    f.write("#!/bin/sh\n")
    f.write("echo 'Downloading {} Kepler targets to {}'\n".format(
        num_kepids, FLAGS.download_dir))
    for i, kepid in enumerate(kepids):
      if i and not i % 10:
        f.write("echo 'Downloaded {}/{}'\n".format(i, num_kepids))
      kepid = "{0:09d}".format(int(kepid))  # Pad with zeros.
      subdir = "{}/{}".format(kepid[0:4], kepid)
      download_dir = os.path.join(FLAGS.download_dir, subdir)
      url = "{}/{}/".format(_BASE_URL, subdir)
      f.write("{} -P {} {}\n".format(_WGET_CMD, download_dir, url))

    f.write("echo 'Finished downloading {} Kepler targets to {}'\n".format(
        num_kepids, FLAGS.download_dir))

  # Make the download script executable.
  os.chmod(FLAGS.output_file, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)

  print("{} Kepler targets will be downloaded to {}".format(
      num_kepids, FLAGS.output_file))
  print("To start download, run:\n  {}".format("./" + FLAGS.output_file
                                               if "/" not in FLAGS.output_file
                                               else FLAGS.output_file)) 
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: test_user.py    From the-littlest-jupyterhub with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ensure_user():
    """
    Test user creation & removal
    """
    # Use a prefix to make sure we never start with a number
    username = 'u' + str(uuid.uuid4())[:8]
    # Validate that no user exists
    with pytest.raises(KeyError):
        pwd.getpwnam(username)

    try:
        # Create user!
        user.ensure_user(username)
        # This raises exception if user doesn't exist
        entry = pwd.getpwnam(username)
        # Home directory must also exist
        home_dir = entry.pw_dir
        assert os.path.exists(home_dir)
        # Ensure not word readable/writable especially in teaching context
        homedir_stats = os.stat(home_dir).st_mode
        assert not (homedir_stats & stat.S_IROTH), "Everyone should not be able to read users home directory"
        assert not (homedir_stats & stat.S_IWOTH), "Everyone should not be able to write users home directory"
        assert not (homedir_stats & stat.S_IXOTH), "Everyone should not be able to list what is in users home directory"

        # Run ensure_user again, should be a noop
        user.ensure_user(username)
        # User still exists, after our second ensure_user call
        pwd.getpwnam(username)
    finally:
        # We clean up and remove user!
        user.remove_user(username)
        with pytest.raises(KeyError):
            pwd.getpwnam(username) 
Example #30
Source File: file.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def activate(self, _f=None):
        """Activate volume."""
        self.po__get_registered_object('auth').assert_permission(PERMISSIONS.MANAGE_STORAGE_VOLUME)
        # Ensure volume exists
        self.ensure_exists()

        require_permissions_if_owned = (
            stat.S_IRUSR | stat.S_IWUSR |
            stat.S_IRGRP | stat.S_IWGRP
        )
        required_permissions_global = (
            stat.S_IROTH | stat.S_IWOTH
        )
        libvirt_config = self.po__get_registered_object('libvirt_config')
        libvirt_user_uid = pwd.getpwnam(libvirt_config.LIBVIRT_USER).pw_uid
        libvirt_group_gid = grp.getgrnam(libvirt_config.LIBVIRT_GROUP).gr_gid
        stat_info = os.stat(self.get_path())

        # Check owner and group of directory
        if ((stat_info.st_uid != libvirt_user_uid or
             stat_info.st_gid != libvirt_group_gid or not
             # Check that libvirt has RWX (user and group)
             (stat_info.st_mode & require_permissions_if_owned ==
              require_permissions_if_owned)) and not
                # Otherwise, Check if 'other' has RWX
                (stat_info.st_mode & required_permissions_global ==
                 required_permissions_global)):

            # User/group are not those required for libvirt and permissions
            # of directory is not 777
            # Attempt to change directory owner/group
            os.chown(self.get_path(), libvirt_user_uid, libvirt_group_gid)
            # Append the required permissions to the current permissions
            os.chmod(self.get_path(), stat_info.st_mode | require_permissions_if_owned)
        return