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


Python os.getuid方法代码示例

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


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

示例1: isUserAdmin

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def isUserAdmin():
    """
    @return: True if the current user is an 'Admin' whatever that means
    (root on Unix), otherwise False.

    Warning: The inner function fails unless you have Windows XP SP2 or
    higher. The failure causes a traceback to be gen.loged and this
    function to return False.
    """

    if platform.system() == "Windows":
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            gen.log("Admin check failed, assuming not an admin.")
            return False
    elif platform.system() == "Linux":
        return os.getuid() == 0
    else:
        raise RuntimeError("Unsupported operating system for this module: %s" % (os.name,)) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:25,代码来源:admin.py

示例2: get_privilege_level

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def get_privilege_level():
	os_type = get_os_type()
	if (os_type == OS_LINUX) or (os_type == OS_MACOSX) or (os_type == OS_FREEBSD):
		if os.getuid() == 0:
			return True
		else:
			return False

	if os_type == OS_WINDOWS:
		import ctypes
		if ctypes.windll.shell32.IsUserAnAdmin():
			return True
		else:
			return False

	return False


# check if the forwarding was set properly. 
开发者ID:earthquake,项目名称:XFLTReaT,代码行数:21,代码来源:common.py

示例3: drop_privileges

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [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

示例4: __init__

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def __init__(self):
        self.cron = CronTab(user=True)
        params = PARAMS % os.getuid()
        filename = os.path.join(os.path.expanduser('~'), FILE)
        desktop_environment = get_desktop_environment()
        if desktop_environment == 'gnome' or \
                desktop_environment == 'unity' or \
                desktop_environment == 'budgie-desktop':
            gset = GSET_GNOME % filename
        elif desktop_environment == "mate":
            gset = GSET_MATE % filename
        elif desktop_environment == "cinnamon":
            gset = GSET_CINNAMON % filename
        else:
            gset = None
        if gset is not None:
            self.command = 'sleep 20;{0};{1} {2} {4} && {3} {4}'.format(
                params, EXEC, SCRIPT, gset, NO_OUTPUT)
        else:
            self.command = None 
开发者ID:atareao,项目名称:daily-wallpaper,代码行数:22,代码来源:croni.py

示例5: get_binary_dir

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def get_binary_dir():
    platform = PLATFORM.copy()
    if platform["os"] == "darwin": # 64 bits anyway on Darwin
        platform["arch"] = "x64"
    elif platform["os"] == "windows": # 32 bits anyway on Windows
        platform["arch"] = "x86"

    binary_dir = os.path.join(RESOURCES_PATH, "bin", "%(os)s_%(arch)s" % platform)

    # On Android, we need to copy torrent2http to ext4, since the sdcard is noexec
    if platform["os"] == "android":

        # Find wether on XBMC or OUYA XBMC
        uid = os.getuid()
        for app_id in ANDROID_XBMC_IDS:
            xbmc_data_path = os.path.join("/data", "data", app_id)
            if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid:
                android_binary_dir = os.path.join(xbmc_data_path, "files", "plugin.video.kmediatorrent")
                break

        if not os.path.exists(android_binary_dir):
            os.makedirs(android_binary_dir)
        binary_dir = android_binary_dir

    return binary_dir 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:27,代码来源:torrent2http.py

示例6: test_permissions_posix

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def test_permissions_posix(self, ipc_server):
        ipc_server.listen()
        sockfile = ipc_server._server.fullServerName()
        sockdir = pathlib.Path(sockfile).parent

        file_stat = os.stat(sockfile)
        dir_stat = sockdir.stat()

        # pylint: disable=no-member,useless-suppression
        file_owner_ok = file_stat.st_uid == os.getuid()
        dir_owner_ok = dir_stat.st_uid == os.getuid()
        # pylint: enable=no-member,useless-suppression
        file_mode_ok = file_stat.st_mode & 0o777 == 0o700
        dir_mode_ok = dir_stat.st_mode & 0o777 == 0o700

        print('sockdir: {} / owner {} / mode {:o}'.format(
            sockdir, dir_stat.st_uid, dir_stat.st_mode))
        print('sockfile: {} / owner {} / mode {:o}'.format(
            sockfile, file_stat.st_uid, file_stat.st_mode))

        assert file_owner_ok or dir_owner_ok
        assert file_mode_ok or dir_mode_ok 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:24,代码来源:test_ipc.py

示例7: closeEvent

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def closeEvent(self, event):
        if (len(self.ThreadDirc['Arp_posion']) != 0) or len(threadloading['template']) !=0:
            reply = QMessageBox.question(self, 'About Exit','Are you sure to close ArpPosion?', QMessageBox.Yes |
                QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                event.accept()
                if getuid() == 0:
                    try:
                        for i in self.ThreadDirc['Arp_posion']:
                            i.stop(),i.join()
                        for i in threadloading['template']:
                            i.stop(),i.join()
                            threadloading['template'] = []
                    except:pass
                    self.deleteLater()
                else:
                    pass
            else:
                event.ignore() 
开发者ID:wi-fi-analyzer,项目名称:3vilTwinAttacker,代码行数:21,代码来源:ModuleArpPosion.py

示例8: getuser

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def getuser():
    """Function to get the username from the environment or password database.

    First try various environment variables, then the password
    database.  This works on Windows as long as USERNAME is set.
    """
    # this is copied from the oroginal getpass.py

    import os

    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        user = os.environ.get(name)
        if user:
            return user

    # If this fails, the exception will "explain" why
    import pwd
    return pwd.getpwuid(os.getuid())[0] 
开发者ID:SergeySatskiy,项目名称:codimension,代码行数:20,代码来源:getpass.py

示例9: valid_config_file

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def valid_config_file(config):
    if not os.path.isabs(config):
        log.error(
            'Error: The config path is not valid. The path must be absolute.')
        exit(1)

    file_owner_uid = os.stat(config).st_uid
    user_uid = os.getuid()
    if user_uid != file_owner_uid and user_uid != 0:
        log.error(
            'Error: The config is not valid. User is not owner of the config or is not root.')
        exit(1)

    mode = stat.S_IMODE(os.stat(config).st_mode)
    other_write_mode = mode & 0b10  # Check if other class write mode flag is set.

    if other_write_mode:
        log.error(
            'Error: The config is not valid. It does not have correct ACLs. '
            'Only owner should be able to write (Hint: try chmod og-rwto fix the problem).'
        )
        exit(1) 
开发者ID:intel,项目名称:workload-collocation-agent,代码行数:24,代码来源:main.py

示例10: shell_lookup

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def shell_lookup():
    """Find an appropriate shell for the user"""
    try:
        usershell = pwd.getpwuid(os.getuid())[6]
    except KeyError:
        usershell = None
    shells = [usershell, 'bash', 'zsh', 'tcsh', 'ksh', 'csh', 'sh']

    for shell in shells:
        if shell is None:
            continue
        elif os.path.isfile(shell):
            return(shell)
        else:
            rshell = path_lookup(shell)
            if rshell is not None:
                dbg('shell_lookup: Found %s at %s' % (shell, rshell))
                return(rshell)
    dbg('shell_lookup: Unable to locate a shell') 
开发者ID:OWASP,项目名称:NINJA-PingU,代码行数:21,代码来源:util.py

示例11: pcocc_run

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def pcocc_run(jobid, jobname, user, indices, script, mirror_env, cmd, timeout, cluster):
    #FIXME: handle pty option once we have agent support
    vms = CLIRangeSet(indices, cluster)

    if not user:
        user = pwd.getpwuid(os.getuid()).pw_name

    cmd = list(cmd)
    if script:
        basename = os.path.basename(cmd[0])
        dest = os.path.join('/tmp', basename)
        writefile(cluster, vms, cmd[0], dest, timeout)
        cmd = ['bash', dest]

    env = []
    if mirror_env:
        for e, v in os.environ.iteritems():
            env.append("{}={}".format(e,v))

    exit_code = multiprocess_call(cluster, vms, cmd, env, user, timeout)

    sys.exit(exit_code) 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:24,代码来源:cmd.py

示例12: get_default_dotm2ee_directory

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def get_default_dotm2ee_directory(self):
        dotm2ee = os.path.join(pwd.getpwuid(os.getuid())[5], ".m2ee")
        if not os.path.isdir(dotm2ee):
            try:
                os.mkdir(dotm2ee)
            except OSError as e:
                logger.debug("Got %s: %s" % (type(e), e))
                import traceback

                logger.debug(traceback.format_exc())
                logger.critical(
                    "Directory %s does not exist, and cannot be " "created!"
                )
                logger.critical(
                    "If you do not want to use .m2ee in your home "
                    "directory, you have to specify pidfile, "
                    "munin -> config_cache in your configuration "
                    "file"
                )
                sys.exit(1)

        return dotm2ee 
开发者ID:mendix,项目名称:cf-mendix-buildpack,代码行数:24,代码来源:config.py

示例13: check_environ

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def check_environ ():
    """Ensure that 'os.environ' has all the environment variables we
    guarantee that users can use in config files, command-line options,
    etc.  Currently this includes:
      HOME - user's home directory (Unix only)
      PLAT - description of the current platform, including hardware
             and OS (see 'get_platform()')
    """
    global _environ_checked
    if _environ_checked:
        return

    if os.name == 'posix' and 'HOME' not in os.environ:
        import pwd
        os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]

    if 'PLAT' not in os.environ:
        os.environ['PLAT'] = get_platform()

    _environ_checked = 1 
开发者ID:glmcdona,项目名称:meddle,代码行数:22,代码来源:util.py

示例14: _find_grail_rc

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [as 别名]
def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
        user = pwd.getpwuid(os.getuid())[0]
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s 
开发者ID:glmcdona,项目名称:meddle,代码行数:27,代码来源:webbrowser.py

示例15: check_enableusersite

# 需要导入模块: import os [as 别名]
# 或者: from os import getuid [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


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