Python os.umask() Examples

The following are 30 code examples of os.umask(). 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: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def _openUploadFile(self, buildId, suffix):
        (packageResultPath, packageResultFile) = self._getPath(buildId, suffix)
        if os.path.isfile(packageResultFile):
            raise ArtifactExistsError()

        # open temporary file in destination directory
        if not os.path.isdir(packageResultPath):
            if self.__dirMode is not None:
                oldMask = os.umask(~self.__dirMode & 0o777)
            try:
                os.makedirs(packageResultPath, exist_ok=True)
            finally:
                if self.__dirMode is not None:
                    os.umask(oldMask)
        return LocalArchiveUploader(
            NamedTemporaryFile(dir=packageResultPath, delete=False),
            self.__fileMode,
            packageResultFile) 
Example #2
Source File: workertmp.py    From jbox with MIT License 6 votes vote down vote up
def __init__(self, cfg):
        old_umask = os.umask(cfg.umask)
        fdir = cfg.worker_tmp_dir
        if fdir and not os.path.isdir(fdir):
            raise RuntimeError("%s doesn't exist. Can't create workertmp." % fdir)
        fd, name = tempfile.mkstemp(prefix="wgunicorn-", dir=fdir)

        # allows the process to write to the file
        util.chown(name, cfg.uid, cfg.gid)
        os.umask(old_umask)

        # unlink the file so we don't leak tempory files
        try:
            if not IS_CYGWIN:
                util.unlink(name)
            self._tmp = os.fdopen(fd, 'w+b', 1)
        except:
            os.close(fd)
            raise

        self.spinner = 0 
Example #3
Source File: config.py    From funcX with Apache License 2.0 6 votes vote down vote up
def write_option(option, value):
    """
    Write an option to disk -- doesn't handle config reloading
    """
    # deny rwx to Group and World -- don't bother storing the returned old mask
    # value, since we'll never restore it in the CLI anyway
    # do this on every call to ensure that we're always consistent about it
    os.umask(0o077)

    conf = get_config_obj()

    # add the section if absent
    if CONF_SECTION_NAME not in conf:
        conf[CONF_SECTION_NAME] = {}

    conf[CONF_SECTION_NAME][option] = value
    conf.write() 
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: daemonize.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=0o022):
        """
        If we're not running under a POSIX system, just simulate the daemon
        mode by doing redirections and directory changing.
        """
        os.chdir(our_home_dir)
        os.umask(umask)
        sys.stdin.close()
        sys.stdout.close()
        sys.stderr.close()
        if err_log:
            sys.stderr = open(err_log, 'a', buffering)
        else:
            sys.stderr = NullDevice()
        if out_log:
            sys.stdout = open(out_log, 'a', buffering)
        else:
            sys.stdout = NullDevice() 
Example #6
Source File: test_mailbox.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_permissions_after_flush(self):
        # See issue #5346

        # Make the mailbox world writable. It's unlikely that the new
        # mailbox file would have these permissions after flush(),
        # because umask usually prevents it.
        mode = os.stat(self._path).st_mode | 0o666
        os.chmod(self._path, mode)

        self._box.add(self._template % 0)
        i = self._box.add(self._template % 1)
        # Need to remove one message to make flush() create a new file
        self._box.remove(i)
        self._box.flush()

        self.assertEqual(os.stat(self._path).st_mode, mode) 
Example #7
Source File: test_mailbox.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_file_perms(self):
        # From bug #3228, we want to verify that the mailbox file isn't executable,
        # even if the umask is set to something that would leave executable bits set.
        # We only run this test on platforms that support umask.
        try:
            old_umask = os.umask(0077)
            self._box.close()
            os.unlink(self._path)
            self._box = mailbox.mbox(self._path, create=True)
            self._box.add('')
            self._box.close()
        finally:
            os.umask(old_umask)

        st = os.stat(self._path)
        perms = st.st_mode
        self.assertFalse((perms & 0111)) # Execute bits should all be off. 
Example #8
Source File: test_dumbdbm.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_dumbdbm_creation_mode(self):
        try:
            old_umask = os.umask(0002)
            f = dumbdbm.open(_fname, 'c', 0637)
            f.close()
        finally:
            os.umask(old_umask)

        expected_mode = 0635
        if os.name != 'posix' or sys.platform == 'cli':
            # Windows and IronPython only support setting the read-only attribute.
            # This shouldn't fail, but doesn't work like Unix either.
            expected_mode = 0666

        import stat
        st = os.stat(_fname + '.dat')
        self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode)
        st = os.stat(_fname + '.dir')
        self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode) 
Example #9
Source File: __init__.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def unzip_file(filename, location, flatten=True):
    """
    Unzip the file (with path `filename`) to the destination `location`.  All
    files are written based on system defaults and umask (i.e. permissions are
    not preserved), except that regular file members with any execute
    permissions (user, group, or world) have "chmod +x" applied after being
    written. Note that for windows, any execute changes using os.chmod are
    no-ops per the python docs.
    """
    ensure_dir(location)
    zipfp = open(filename, 'rb')
    try:
        zip = zipfile.ZipFile(zipfp, allowZip64=True)
        leading = has_leading_dir(zip.namelist()) and flatten
        for info in zip.infolist():
            name = info.filename
            data = zip.read(name)
            fn = name
            if leading:
                fn = split_leading_dir(name)[1]
            fn = os.path.join(location, fn)
            dir = os.path.dirname(fn)
            if fn.endswith('/') or fn.endswith('\\'):
                # A directory
                ensure_dir(fn)
            else:
                ensure_dir(dir)
                fp = open(fn, 'wb')
                try:
                    fp.write(data)
                finally:
                    fp.close()
                    mode = info.external_attr >> 16
                    # if mode and regular file and any execute permissions for
                    # user/group/world?
                    if mode and stat.S_ISREG(mode) and mode & 0o111:
                        # make dest file have execute for user/group/world
                        # (chmod +x) no-op on windows per python docs
                        os.chmod(fn, (0o777 - current_umask() | 0o111))
    finally:
        zipfp.close() 
Example #10
Source File: file.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def _create_file_if_needed(self):
    """Create an empty file if necessary.

    This method will not initialize the file. Instead it implements a
    simple version of "touch" to ensure the file has been created.
    """
    if not os.path.exists(self._filename):
      old_umask = os.umask(0177)
      try:
        open(self._filename, 'a+b').close()
      finally:
        os.umask(old_umask) 
Example #11
Source File: multistore_file.py    From splunk-ref-pas-code with Apache License 2.0 5 votes vote down vote up
def _create_file_if_needed(self):
    """Create an empty file if necessary.

    This method will not initialize the file. Instead it implements a
    simple version of "touch" to ensure the file has been created.
    """
    if not os.path.exists(self._file.filename()):
      old_umask = os.umask(0177)
      try:
        open(self._file.filename(), 'a+b').close()
      finally:
        os.umask(old_umask) 
Example #12
Source File: util.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def get_process_umask():
    result = os.umask(0o22)
    os.umask(result)
    return result 
Example #13
Source File: __init__.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def current_umask():
    """Get the current umask which involves having to set it temporarily."""
    mask = os.umask(0)
    os.umask(mask)
    return mask 
Example #14
Source File: multistore_file.py    From sndlatr with Apache License 2.0 5 votes vote down vote up
def _create_file_if_needed(self):
    """Create an empty file if necessary.

    This method will not initialize the file. Instead it implements a
    simple version of "touch" to ensure the file has been created.
    """
    if not os.path.exists(self._file.filename()):
      old_umask = os.umask(0177)
      try:
        open(self._file.filename(), 'a+b').close()
      finally:
        os.umask(old_umask) 
Example #15
Source File: util.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def get_process_umask():
    result = os.umask(0o22)
    os.umask(result)
    return result 
Example #16
Source File: misc.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def unzip_file(filename, location, flatten=True):
    """
    Unzip the file (with path `filename`) to the destination `location`.  All
    files are written based on system defaults and umask (i.e. permissions are
    not preserved), except that regular file members with any execute
    permissions (user, group, or world) have "chmod +x" applied after being
    written. Note that for windows, any execute changes using os.chmod are
    no-ops per the python docs.
    """
    ensure_dir(location)
    zipfp = open(filename, 'rb')
    try:
        zip = zipfile.ZipFile(zipfp, allowZip64=True)
        leading = has_leading_dir(zip.namelist()) and flatten
        for info in zip.infolist():
            name = info.filename
            data = zip.read(name)
            fn = name
            if leading:
                fn = split_leading_dir(name)[1]
            fn = os.path.join(location, fn)
            dir = os.path.dirname(fn)
            if fn.endswith('/') or fn.endswith('\\'):
                # A directory
                ensure_dir(fn)
            else:
                ensure_dir(dir)
                fp = open(fn, 'wb')
                try:
                    fp.write(data)
                finally:
                    fp.close()
                    mode = info.external_attr >> 16
                    # if mode and regular file and any execute permissions for
                    # user/group/world?
                    if mode and stat.S_ISREG(mode) and mode & 0o111:
                        # make dest file have execute for user/group/world
                        # (chmod +x) no-op on windows per python docs
                        os.chmod(fn, (0o777 - current_umask() | 0o111))
    finally:
        zipfp.close() 
Example #17
Source File: misc.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def current_umask():
    """Get the current umask which involves having to set it temporarily."""
    mask = os.umask(0)
    os.umask(mask)
    return mask 
Example #18
Source File: file.py    From splunk-ref-pas-code with Apache License 2.0 5 votes vote down vote up
def _create_file_if_needed(self):
    """Create an empty file if necessary.

    This method will not initialize the file. Instead it implements a
    simple version of "touch" to ensure the file has been created.
    """
    if not os.path.exists(self._filename):
      old_umask = os.umask(0177)
      try:
        open(self._filename, 'a+b').close()
      finally:
        os.umask(old_umask) 
Example #19
Source File: test_plugins.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_jar_container_crawler_avoidsetns(self, *args):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            fc = JarContainerCrawler()
            jars = list(fc.crawl(root_dir=os.path.basename(tmpdir), avoid_setns=True))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path) 
Example #20
Source File: test_plugins.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_jar_container_crawler_plugin(self, *args):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            fc = JarContainerCrawler()
            jars = list(fc.crawl(root_dir=tmpdir))
            #jars = list(jar_utils.crawl_jar_files(root_dir=tmpdir))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path) 
Example #21
Source File: test_jar_plugin.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_jar_host_crawler_plugin(self, *args):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            fc = JarHostCrawler()
            jars = list(fc.crawl(root_dir=tmpdir))
            #jars = list(jar_utils.crawl_jar_files(root_dir=tmpdir))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path)
            os.umask(saved_umask) 
Example #22
Source File: test_jar_utils.py    From agentless-system-crawler with Apache License 2.0 5 votes vote down vote up
def test_get_jar_features(self):
        tmpdir = tempfile.mkdtemp()
        jar_file_name = 'myfile.jar'

        # Ensure the file is read/write by the creator only
        saved_umask = os.umask(0077)

        path = os.path.join(tmpdir, jar_file_name)
        try:
            with ZipFile(path, "w") as myjar:
                myjar.writestr(ZipInfo('first.class',(1980,1,1,1,1,1)), "first secrets!")
                myjar.writestr(ZipInfo('second.class',(1980,1,1,1,1,1)), "second secrets!")
                myjar.writestr(ZipInfo('second.txt',(1980,1,1,1,1,1)), "second secrets!")

            jars = list(jar_utils.crawl_jar_files(root_dir=tmpdir))
            print jars
            jar_feature = jars[0][1]
            assert 'myfile.jar' == jar_feature.name
            assert '48ac85a26ffa7ff5cefdd5c73a9fb888' == jar_feature.jarhash
            assert ['ddc6eff37020aa858e26b1ba8a49ee0e',
                    'cbe2a13eb99c1c8ac5f30d0a04f8c492'] == jar_feature.hashes
            assert 'jar' == jars[0][2]

        except IOError as e:
            print 'IOError'
        finally:
            os.remove(path)
            os.umask(saved_umask)
            os.rmdir(tmpdir) 
Example #23
Source File: easy_install.py    From lambda-chef-node-cleanup with Apache License 2.0 5 votes vote down vote up
def current_umask():
    tmp = os.umask(0o022)
    os.umask(tmp)
    return tmp 
Example #24
Source File: easy_install.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def current_umask():
    tmp = os.umask(0o022)
    os.umask(tmp)
    return tmp 
Example #25
Source File: test_mailbox.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_file_permissions(self):
        # Verify that message files are created without execute permissions
        msg = mailbox.MaildirMessage(self._template % 0)
        orig_umask = os.umask(0)
        try:
            key = self._box.add(msg)
        finally:
            os.umask(orig_umask)
        path = os.path.join(self._path, self._box._lookup(key))
        mode = os.stat(path).st_mode
        self.assertEqual(mode & 0111, 0) 
Example #26
Source File: test_tarfile.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_file_mode(self):
        # Test for issue #8464: Create files with correct
        # permissions.
        if os.path.exists(tmpname):
            os.remove(tmpname)

        original_umask = os.umask(0022)
        try:
            tar = tarfile.open(tmpname, self.mode)
            tar.close()
            mode = os.stat(tmpname).st_mode & 0777
            self.assertEqual(mode, 0644, "wrong file permissions")
        finally:
            os.umask(original_umask) 
Example #27
Source File: dumbdbm.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def open(file, flag=None, mode=0666):
    """Open the database file, filename, and return corresponding object.

    The flag argument, used to control how the database is opened in the
    other DBM implementations, is ignored in the dumbdbm module; the
    database is always opened for update, and will be created if it does
    not exist.

    The optional mode argument is the UNIX mode of the file, used only when
    the database has to be created.  It defaults to octal code 0666 (and
    will be modified by the prevailing umask).

    """
    # flag argument is currently ignored

    # Modify mode depending on the umask
    try:
        um = _os.umask(0)
        _os.umask(um)
    except AttributeError:
        pass
    else:
        # Turn off any bits that are set in the umask
        mode = mode & (~um)

    return _Database(file, mode, flag) 
Example #28
Source File: test_dir_util.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_mkpath_with_custom_mode(self):
        # Get and set the current umask value for testing mode bits.
        umask = os.umask(0o002)
        os.umask(umask)
        mkpath(self.target, 0o700)
        self.assertEqual(
            stat.S_IMODE(os.stat(self.target).st_mode), 0o700 & ~umask)
        mkpath(self.target2, 0o555)
        self.assertEqual(
            stat.S_IMODE(os.stat(self.target2).st_mode), 0o555 & ~umask) 
Example #29
Source File: test_utils_dirhasher.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        os.umask(self.umask) 
Example #30
Source File: os_utils.py    From godot-mono-builds with MIT License 5 votes vote down vote up
def chmod_plus_x(file):
    import os
    import stat
    umask = os.umask(0)
    os.umask(umask)
    st = os.stat(file)
    os.chmod(file, st.st_mode | ((stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) & ~umask))