Python os.umask() Examples

The following are 30 code examples for showing how to use os.umask(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: certidude   Author: laurivosandi   File: common.py    License: MIT License 6 votes vote down vote up
def drop_privileges():
    from certidude import config
    import pwd
    _, _, uid, gid, gecos, root, shell = pwd.getpwnam("certidude")
    restricted_groups = []
    restricted_groups.append(gid)

    # PAM needs access to /etc/shadow
    if config.AUTHENTICATION_BACKENDS == {"pam"}:
        import grp
        name, passwd, num, mem = grp.getgrnam("shadow")
        click.echo("Adding current user to shadow group due to PAM authentication backend")
        restricted_groups.append(num)

    os.setgroups(restricted_groups)
    os.setgid(gid)
    os.setuid(uid)
    click.echo("Switched %s (pid=%d) to user %s (uid=%d, gid=%d); member of groups %s" %
        (getproctitle(), os.getpid(), "certidude", os.getuid(), os.getgid(), ", ".join([str(j) for j in os.getgroups()])))
    os.umask(0o007) 
Example 2
Project: jbox   Author: jpush   File: workertmp.py    License: 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
Project: funcX   Author: funcx-faas   File: config.py    License: 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
Project: GTDWeb   Author: lanbing510   File: daemonize.py    License: 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 5
Project: bob   Author: BobBuildTool   File: archive.py    License: 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 6
Project: ironpython2   Author: IronLanguages   File: test_import.py    License: 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 7
Project: ironpython2   Author: IronLanguages   File: test_mailbox.py    License: 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 8
Project: ironpython2   Author: IronLanguages   File: test_mailbox.py    License: 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 9
Project: ironpython2   Author: IronLanguages   File: test_dumbdbm.py    License: 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 10
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    License: 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)) 
Example 11
Project: cherrypy   Author: cherrypy   File: plugins.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, bus, umask=None, uid=None, gid=None):
        SimplePlugin.__init__(self, bus)
        self.finalized = False
        self.uid = uid
        self.gid = gid
        self.umask = umask 
Example 12
Project: cherrypy   Author: cherrypy   File: plugins.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def umask(self):
        """The default permission mode for newly created files and directories.

        Usually expressed in octal format, for example, ``0644``.
        Availability: Unix, Windows.
        """
        return self._umask 
Example 13
Project: cherrypy   Author: cherrypy   File: plugins.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def umask(self, val):
        if val is not None:
            try:
                os.umask
            except AttributeError:
                self.bus.log('umask function not available; ignoring umask.',
                             level=30)
                val = None
        self._umask = val 
Example 14
Project: jawfish   Author: war-and-code   File: support.py    License: MIT License 5 votes vote down vote up
def temp_umask(umask):
        """Context manager that temporarily sets the process umask."""
        oldmask = os.umask(umask)
        try:
            yield
        finally:
            os.umask(oldmask) 
Example 15
Project: verge3d-blender-addon   Author: Soft8Soft   File: support.py    License: GNU General Public License v3.0 5 votes vote down vote up
def temp_umask(umask):
        """Context manager that temporarily sets the process umask."""
        oldmask = os.umask(umask)
        try:
            yield
        finally:
            os.umask(oldmask) 
Example 16
Project: bilibiliupload   Author: ForgQi   File: Daemon.py    License: MIT License 5 votes vote down vote up
def _daemonize(self):
        try:
            pid = os.fork()  # 第一次fork,生成子进程,脱离父进程
            if pid > 0:
                sys.exit(0)  # 退出主进程
        except OSError as e:
            sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
            sys.exit(1)

        if self.cd:
            os.chdir("/")  # 修改工作目录
        os.setsid()  # 设置新的会话连接
        os.umask(0)  # 重新设置文件创建权限

        try:
            pid = os.fork()  # 第二次fork,禁止进程打开终端
            if pid > 0:
                sys.exit(0)
        except OSError as e:
            sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
            sys.exit(1)

        # 重定向文件描述符
        sys.stdout.flush()
        sys.stderr.flush()
        # with open(self.stdin, 'r') as si, open(self.stdout, 'a+') as so, open(self.stderr, 'ab+', 0) as se:
        si = open(self.stdin, 'r')
        so = open(self.stdout, 'a+')
        se = open(self.stderr, 'ab+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # 注册退出函数,根据文件pid判断是否存在进程
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as f:
            f.write('%s\n' % pid)
            # file(self.pidfile, 'w+').write('%s\n' % pid) 
Example 17
Project: recruit   Author: Frank-qlu   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def get_process_umask():
    result = os.umask(0o22)
    os.umask(result)
    return result 
Example 18
Project: recruit   Author: Frank-qlu   File: __init__.py    License: 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 19
Project: recruit   Author: Frank-qlu   File: __init__.py    License: 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 20
Project: jbox   Author: jpush   File: util.py    License: MIT License 5 votes vote down vote up
def get_process_umask():
    result = os.umask(0o22)
    os.umask(result)
    return result 
Example 21
Project: jbox   Author: jpush   File: __init__.py    License: 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 22
Project: jbox   Author: jpush   File: __init__.py    License: 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 23
Project: jbox   Author: jpush   File: easy_install.py    License: MIT License 5 votes vote down vote up
def current_umask():
    tmp = os.umask(0o022)
    os.umask(tmp)
    return tmp 
Example 24
Project: rucio   Author: rucio   File: pcache.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self):
        os.umask(0)
        self.storage_root = "/pnfs"
        self.scratch_dir = "/scratch/"
        self.pcache_dir = self.scratch_dir + "pcache/"
        self.log_file = self.pcache_dir + "pcache.log"
        self.max_space = "80%"
        self.percent_max = None
        self.bytes_max = None
        # self.max_space = "10T"
        self.hysterisis = 0.75
        # self.hysterisis = 0.9
        self.clean = False
        self.transfer_timeout = "600"
        self.max_retries = 3
        self.guid = None
        self.accept_patterns = []
        self.reject_patterns = []
        self.force = False
        self.flush = False
        self.verbose = False
        self.quiet = False
        self.debug = False
        self.hostname = None
        self.sitename = None  # XXX can we get this from somewhere?
        self.update_panda = False
        self.panda_url = "https://pandaserver.cern.ch:25443/server/panda/"
        self.local_src = None
        self.skip_download = False

        # internal variables
        self.sleep_interval = 15
        self.force = False
        self.locks = {}
        self.deleted_guids = []
        self.version = pcacheversion 
Example 25
Project: rucio   Author: rucio   File: pcache.py    License: Apache License 2.0 5 votes vote down vote up
def daemonize(self):
        if self.debug:
            return
        try:
            os.setsid()
        except OSError:
            pass
        try:
            os.chdir("/")
        except OSError:
            pass
        try:
            os.umask(0)
        except OSError:
            pass
        n = os.open("/dev/null", os.O_RDWR)
        i, o, e = sys.stdin.fileno(), sys.stdout.fileno(), sys.stderr.fileno()
        os.dup2(n, i)
        os.dup2(n, o)
        os.dup2(n, e)
        MAXFD = 1024
        try:
            import resource  # Resource usage information.
            maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
            if (maxfd == resource.RLIM_INFINITY):
                maxfd = MAXFD
        except:
            try:
                maxfd = os.sysconf("SC_OPEN_MAX")
            except:
                maxfd = MAXFD  # use default value

        for fd in range(0, maxfd + 1):
            try:
                os.close(fd)
            except:
                pass

    # Panda server callback functions 
Example 26
Project: earthengine   Author: mortcanty   File: file.py    License: MIT License 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 27
Project: earthengine   Author: mortcanty   File: multistore_file.py    License: MIT License 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 28
Project: insightconnect-plugins   Author: rapid7   File: connection.py    License: MIT License 5 votes vote down vote up
def temp_umask(umask):
    oldmask = os.umask(umask)
    try:
        yield
    finally:
        os.umask(oldmask) 
Example 29
Project: GTDWeb   Author: lanbing510   File: daemonize.py    License: GNU General Public License v2.0 5 votes vote down vote up
def become_daemon(our_home_dir='.', out_log='/dev/null',
                      err_log='/dev/null', umask=0o022):
        "Robustly turn into a UNIX daemon, running in our_home_dir."
        # First fork
        try:
            if os.fork() > 0:
                sys.exit(0)     # kill off parent
        except OSError as e:
            sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
            sys.exit(1)
        os.setsid()
        os.chdir(our_home_dir)
        os.umask(umask)

        # Second fork
        try:
            if os.fork() > 0:
                os._exit(0)
        except OSError as e:
            sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
            os._exit(1)

        si = open('/dev/null', 'r')
        so = open(out_log, 'a+', buffering)
        se = open(err_log, 'a+', buffering)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())
        # Set custom file descriptors so that they get proper buffering.
        sys.stdout, sys.stderr = so, se 
Example 30
Project: python-netsurv   Author: sofia-netsurv   File: __init__.py    License: 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