当前位置: 首页>>代码示例>>Python>>正文


Python os.getgid方法代码示例

本文整理汇总了Python中os.getgid方法的典型用法代码示例。如果您正苦于以下问题:Python os.getgid方法的具体用法?Python os.getgid怎么用?Python os.getgid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


在下文中一共展示了os.getgid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
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) 
开发者ID:laurivosandi,项目名称:certidude,代码行数:22,代码来源:common.py

示例2: check_enableusersite

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if sys.flags.no_user_site:
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
开发者ID:glmcdona,项目名称:meddle,代码行数:25,代码来源:site.py

示例3: testNoArgFunctions

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def testNoArgFunctions(self):
        # test posix functions which take no arguments and have
        # no side-effects which we need to cleanup (e.g., fork, wait, abort)
        NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname",
                             "times", "getloadavg", "tmpnam",
                             "getegid", "geteuid", "getgid", "getgroups",
                             "getpid", "getpgrp", "getppid", "getuid",
                           ]

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "", DeprecationWarning)
            for name in NO_ARG_FUNCTIONS:
                posix_func = getattr(posix, name, None)
                if posix_func is not None:
                    posix_func()
                    self.assertRaises(TypeError, posix_func, 1) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:test_posix.py

示例4: check_enableusersite

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:25,代码来源:site.py

示例5: is_writable

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def is_writable(path):
  # Ensure that it exists.
  if not os.path.exists(path):
    return False

  # If we're on a posix system, check its permissions.
  if hasattr(os, 'getuid'):
    statdata = os.stat(path)
    perm = stat.S_IMODE(statdata.st_mode)
    # is it world-writable?
    if (perm & 0o002):
      return True
    # do we own it?
    elif statdata.st_uid == os.getuid() and (perm & 0o200):
      return True
    # are we in a group that can write to it?
    elif (statdata.st_gid in [os.getgid()] + os.getgroups()) and (perm & 0o020):
      return True
    # otherwise, we can't write to it.
    else:
      return False

  # Otherwise, we'll assume it's writable.
  # [xx] should we do other checks on other platforms?
  return True 
开发者ID:aboSamoor,项目名称:polyglot,代码行数:27,代码来源:downloader.py

示例6: whoami

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def whoami(check_sudo: bool = True) -> dict:
    """
    Get the dictionary of current user info
    :param check_sudo: True, if you want get the user which executed sudo command
    :return: A dictionary with current user info
    """
    name = None
    uid = None
    gid = None
    sudo = True
    if check_sudo:
        name = os.environ.get('SUDO_USER')
        uid = os.environ.get('SUDO_UID')
        gid = os.environ.get('SUDO_GID')
    if name is None:
        sudo = False
        name = getpass.getuser()
        uid = os.getuid()
        gid = os.getgid()
    return {
        'name': str(name),
        'uid': int(uid),
        'gid': int(gid),
        'sudo': sudo
    } 
开发者ID:offensive-hub,项目名称:black-widow,代码行数:27,代码来源:util.py

示例7: _run_jupyter

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def _run_jupyter(self, runner: ArmoryInstance, ports: dict) -> None:
        user_id = os.getuid() if os.name != "nt" else 0
        group_id = os.getgid() if os.name != "nt" else 0
        port = list(ports.keys())[0]
        lines = [
            "About to launch jupyter.",
            bold("*** To connect on the command line as well, in a new terminal, run:"),
            bold(
                f"    docker exec -it -u {user_id}:{group_id} {runner.docker_container.short_id} bash"
            ),
            bold("*** To gracefully shut down container, press: Ctrl-C"),
            "",
            "Jupyter notebook log:",
        ]
        logger.info("\n".join(lines))
        runner.exec_cmd(
            f"jupyter lab --ip=0.0.0.0 --port {port} --no-browser --allow-root",
            user="root",
        ) 
开发者ID:twosixlabs,项目名称:armory,代码行数:21,代码来源:evaluator.py

示例8: restore_lxpanel_configuration

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def restore_lxpanel_configuration(self):
        userid = os.getuid()
        groupid = os.getgid()
        original_lxpanel_path = '/etc/skel/.config/lxpanel/'
        user_lxpanel_path = os.path.join('/home/' + os.getenv('SUDO_USER'), '.config/lxpanel')

        # remove the current local copy
        shutil.rmtree(user_lxpanel_path, ignore_errors=True)

        # re-create the copy from the skeleton
        shutil.copytree(original_lxpanel_path, user_lxpanel_path, symlinks=False, ignore=None)
        for root, dirs, files in os.walk(user_lxpanel_path):
            for name in files:
                os.chown(os.path.join(root, name), userid, groupid)

        run_cmd('lxpanelctl restart') 
开发者ID:KanoComputing,项目名称:kano-settings,代码行数:18,代码来源:set_style.py

示例9: check_enableusersite

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if hasattr(sys, "flags") and getattr(sys.flags, "no_user_site", False):
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
开发者ID:QData,项目名称:deepWordBug,代码行数:25,代码来源:site.py

示例10: fuse_main

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def fuse_main(self, mount_point):
        self.__class__.__name__ = 'oxfs'
        if 'Darwin' == self.sys:
            fuse = FUSE(self, mount_point, foreground=True, nothreads=True,
                        allow_other=True, auto_cache=True,
                        uid=os.getuid(), gid=os.getgid(),
                        defer_permissions=True, kill_on_unmount=True,
                        noappledouble=True, noapplexattr=True,
                        nosuid=True, nobrowse=True, volname=self.host)
        elif 'Linux' == self.sys:
            fuse = FUSE(self, mount_point, foreground=True, nothreads=True,
                        allow_other=True, auto_cache=True,
                        uid=os.getuid(), gid=os.getgid(),
                        auto_unmount=True)
        else:
            self.logger.error('not supported system, {}'.format(self.sys))
            sys.exit() 
开发者ID:RainMark,项目名称:oxfs,代码行数:19,代码来源:oxfs.py

示例11: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
    try: import pwd, grp
    except ImportError: return False # Windows

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    running_uid_home = pwd.getpwnam(uid_name).pw_dir
    running_gid = grp.getgrnam(gid_name).gr_gid

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(running_gid)
    os.setuid(running_uid)

    # Ensure a very conservative umask
    old_umask = os.umask(int('077', 8))
    value = (os.getuid() == running_uid and os.getgid() == running_gid)
    if value:  # could be useful
       os.environ['HOME'] = running_uid_home
       logger.info('Changed permissions to: %s: %i, %s, %i' % (uid_name, running_uid, gid_name, running_gid))
    return value 
开发者ID:pepsik-kiev,项目名称:HTTPAceProxy,代码行数:25,代码来源:acehttp.py

示例12: test_is_readable

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def test_is_readable(fs, value, fails, allow_empty):
    """Test checkers.is_readable()"""
    expects = not fails
    if value:
        fs.create_file(value)

    if fails and sys.platform in ['linux', 'linux2', 'darwin']:
        if value:
            real_uid = os.getuid()
            real_gid = os.getgid()
            fake_uid = real_uid
            fake_gid = real_gid
            while fake_uid == real_uid:
                fake_uid = int(random.random() * 100)

            while fake_gid == real_gid:
                fake_gid = int(random.random() * 100)

            os.chown(value, fake_uid, fake_gid)
            os.chmod(value, 0o027)
    elif fails and sys.platform in ['win32', 'cygwin']:
        expects = bool(value)

    result = checkers.is_readable(value)
    assert result == expects 
开发者ID:insightindustry,项目名称:validator-collection,代码行数:27,代码来源:test_checkers.py

示例13: test_stats

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def test_stats(self):
        commit = self.get_commits_by_date()[0]
        directory = "{}/history/{}/{}".format(self.mount_path, self.today, commit)
        filename = "{}/testing".format(directory)

        stats = os.stat(filename)

        attrs = {"st_uid": os.getuid(), "st_gid": os.getgid(), "st_mode": 0o100444}

        for name, value in iteritems(attrs):
            assert getattr(stats, name) == value

        st_time = "{} {}".format(self.today, "-".join(commit.split("-")[:-1]))

        format = "%Y-%m-%d %H-%M-%S"
        ctime = datetime.fromtimestamp(stats.st_ctime).strftime(format)
        mtime = datetime.fromtimestamp(stats.st_ctime).strftime(format)

        assert ctime == st_time
        assert mtime == st_time 
开发者ID:presslabs,项目名称:gitfs,代码行数:22,代码来源:test_read.py

示例14: test_get_correct_stats

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def test_get_correct_stats(self):
        filename = "{}/testing".format(self.current_path)
        stats = os.stat(filename)

        filename = "{}/testing".format(self.repo_path)
        real_stats = os.stat(filename)

        attrs = {
            "st_uid": os.getuid(),
            "st_gid": os.getgid(),
            "st_mode": 0o100644,
            "st_ctime": real_stats.st_ctime,
            "st_mtime": real_stats.st_mtime,
            "st_atime": real_stats.st_atime,
        }

        for name, value in iteritems(attrs):
            assert getattr(stats, name) == value 
开发者ID:presslabs,项目名称:gitfs,代码行数:20,代码来源:test_read.py

示例15: clean_client

# 需要导入模块: import os [as 别名]
# 或者: from os import getgid [as 别名]
def clean_client():
    assert os.getuid() == 0 and os.getgid() == 0
    files = [
        "/etc/certidude/client.conf",
        "/etc/certidude/services.conf",
        "/etc/certidude/client.conf.d/ca.conf",
        "/etc/certidude/services.conf.d/ca.conf",
        "/etc/certidude/authority/ca.example.lan/ca_cert.pem",
        "/etc/certidude/authority/ca.example.lan/client_key.pem",
        "/etc/certidude/authority/ca.example.lan/server_key.pem",
        "/etc/certidude/authority/ca.example.lan/client_req.pem",
        "/etc/certidude/authority/ca.example.lan/server_req.pem",
        "/etc/certidude/authority/ca.example.lan/client_cert.pem",
        "/etc/certidude/authority/ca.example.lan/server_cert.pem",
        "/etc/NetworkManager/system-connections/IPSec to ipsec.example.lan",
        "/etc/NetworkManager/system-connections/OpenVPN to vpn.example.lan",
    ]
    for path in files:
        if os.path.exists(path):
            os.unlink(path)

    # Remove client storage area
    if os.path.exists("/tmp/ca.example.lan"):
        for filename in os.listdir("/tmp/ca.example.lan"):
            if filename.endswith(".pem"):
                os.unlink(os.path.join("/tmp/ca.example.lan", filename))

    # Reset IPsec stuff
    with open("/etc/ipsec.conf", "w") as fh: # TODO: make compatible with Fedora
        pass
    with open("/etc/ipsec.secrets", "w") as fh: # TODO: make compatible with Fedora
        pass 
开发者ID:laurivosandi,项目名称:certidude,代码行数:34,代码来源:test_cli.py


注:本文中的os.getgid方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。