Python os.getuid() Examples

The following are 30 code examples of os.getuid(). 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: common.py    From XFLTReaT with MIT License 7 votes vote down vote up
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. 
Example #2
Source File: util.py    From meddle with MIT License 6 votes vote down vote up
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 
Example #3
Source File: site.py    From meddle with MIT License 6 votes vote down vote up
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 
Example #4
Source File: __main__.py    From wifite2mod with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self):
        '''
        Initializes Wifite. Checks for root permissions and ensures dependencies are installed.
        '''

        self.print_banner()

        Configuration.initialize(load_interface=False)

        if os.getuid() != 0:
            Color.pl('{!} {R}error: {O}wifite{R} must be run as {O}root{W}')
            Color.pl('{!} {R}re-run with {O}sudo{W}')
            Configuration.exit_gracefully(0)

        from .tools.dependency import Dependency
        Dependency.run_dependency_check() 
Example #5
Source File: webbrowser.py    From meddle with MIT License 6 votes vote down vote up
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 
Example #6
Source File: privilege.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def _helper_installer(action):
    if action not in ('install', 'uninstall'):
        raise Exception('Wrong action: %s' % action)

    if IS_LINUX:
        if IS_SNAP:
            log.debug('Skipping install of helpers, '
                      'snap should have done that')
            return
        cmd = 'bitmask_helpers ' + action
        if STANDALONE:
            binary_path = os.path.join(here(), "bitmask")
            cmd = "%s %s" % (binary_path, cmd)
        if os.getuid() != 0:
            cmd = 'pkexec ' + cmd
        retcode, output = commands.getstatusoutput(cmd)
        if retcode != 0:
            log.error('Error installing/uninstalling helpers: %s' % output)
            log.error('Command was: %s' % cmd)
            raise Exception('Could not install/uninstall helpers')
    else:
        raise Exception('No install mechanism for this platform') 
Example #7
Source File: croni.py    From daily-wallpaper with MIT License 6 votes vote down vote up
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 
Example #8
Source File: torrent2http.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: test_ipc.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #10
Source File: config.py    From cf-mendix-buildpack with Apache License 2.0 6 votes vote down vote up
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 
Example #11
Source File: ModuleArpPosion.py    From 3vilTwinAttacker with MIT License 6 votes vote down vote up
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() 
Example #12
Source File: cmd.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: getpass.py    From codimension with GNU General Public License v3.0 6 votes vote down vote up
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] 
Example #14
Source File: main.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
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) 
Example #15
Source File: util.py    From NINJA-PingU with GNU General Public License v3.0 6 votes vote down vote up
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') 
Example #16
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def gethomedir(self, username):
        if not username:
            try:
                return os.environ['HOME']
            except KeyError:
                import pwd
                return pwd.getpwuid(os.getuid()).pw_dir
        else:
            import pwd
            try:
                return pwd.getpwnam(username).pw_dir
            except KeyError:
                raise RuntimeError("Can't determine home directory "
                                   "for %r" % username) 
Example #17
Source File: __init__.py    From python-netsurv with MIT License 5 votes vote down vote up
def gethomedir(self, username):
        if not username:
            try:
                return os.environ['HOME']
            except KeyError:
                import pwd
                return pwd.getpwuid(os.getuid()).pw_dir
        else:
            import pwd
            try:
                return pwd.getpwnam(username).pw_dir
            except KeyError:
                raise RuntimeError("Can't determine home directory "
                                   "for %r" % username) 
Example #18
Source File: application.py    From exaddos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def drop_privileges (configuration):
	# os.name can be ['posix', 'nt', 'os2', 'ce', 'java', 'riscos']
	if os.name not in ['posix',]:
		return True

	if os.getuid() != 0:
		err('not running as root, not changing UID')
		return True

	users = [configuration.daemon.user,'nobody']

	for user in users:
		if __drop_privileges(user):
			return True
	return False 
Example #19
Source File: cmd.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def pcocc_exec(index, jobid, jobname, user, script, cmd):
    """Execute commands through the guest agent

       For this to work, a pcocc agent must be started in the
       guest. This is mostly available for internal use where we do
       not want to rely on a network connexion / ssh server.
    """
    try:
        load_config(jobid, jobname, default_batchname='pcocc')
        cluster = load_batch_cluster()

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

        cmd = list(cmd)

        if script:
            basename = os.path.basename(cmd[0])
            cluster.vms[index].put_file(cmd[0],
                                    '/tmp/%s' % basename)
            cmd = ['bash', '/tmp/%s' % basename]

        ret = cluster.exec_cmd([index], cmd, user)
        sys.exit(max(ret))

    except PcoccError as err:
        handle_error(err) 
Example #20
Source File: Batch.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def _get_keyval_username(self):
        if self._etcd_auth_type == 'none':
            return None
        else:
            return pwd.getpwuid(os.getuid()).pw_name 
Example #21
Source File: Config.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def resolve_path(self, path, vm=None):
        """ Resolve a path from a custom template string
        %{env:ENVVAR}   is expanded to the content of the environment variable ENVVAR
        %{clusterdir}   to a temporary directory to store per-cluster data
        %{vm_rank}      to the rank of the virtual machine
        %{user}         to the current user name
        %{homedir}      to home directory of the current user
        %{clusterowner} to the user name of the cluster owner
        """
        tpl = TemplatePath(path)
        tplvalues = {}

        try:
            tplvalues['clusterdir']  = self.batch.cluster_state_dir
            tplvalues['clusteruser'] = self.batch.batchuser
        except AttributeError:
            pass

        for key, val in os.environ.iteritems():
            tplvalues['env:%s' % (key)] = val

        tplvalues['homedir'] =  expanduser("~")
        tplvalues['user'] =  pwd.getpwuid(os.getuid()).pw_name

        if vm:
            tplvalues['vm_rank'] = vm.rank

        return expanduser(tpl.safe_substitute(tplvalues)) 
Example #22
Source File: _logging.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def _get_log_dirs():
    log_dirs = [SYSTEM_LOGS_DIR]
    if os.getuid() != 0:
        log_dirs.append(USER_LOGS_DIR)
    else:
        for f in os.listdir('/home'):
            user_log_dir = '/home/{}/.kano-logs'.format(f)
            if os.path.isdir(user_log_dir):
                log_dirs.append(user_log_dir)
    return log_dirs 
Example #23
Source File: _logging.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def _init_log_file(self):
        if self._log_file is not None:
            self._log_file.close()

        if os.getuid() == 0 and not is_sudoed:
            logs_dir = SYSTEM_LOGS_DIR
        else:
            logs_dir = USER_LOGS_DIR

        if not os.path.exists(logs_dir):
            os.makedirs(logs_dir)

            # Fix permissions in case we need to create the dir with sudo
            if is_sudoed:
                uid = pwd.getpwnam(usr).pw_uid
                gid = grp.getgrnam(usr).gr_gid
                os.chown(logs_dir, uid, gid)

        log_fn = "{}/{}.log".format(logs_dir, self._app_name)

        # Fix permissions in case we need to create the file with sudo
        if not os.path.isfile(log_fn) and is_sudoed:
            # touch
            with open(log_fn, 'a'):
                pass

            uid = pwd.getpwnam(usr).pw_uid
            gid = grp.getgrnam(usr).gr_gid
            os.chown(log_fn, uid, gid)

        self._log_file = open("{}/{}.log".format(logs_dir, self._app_name), "a") 
Example #24
Source File: network.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def launch_browser(*args):
    # TODO: Set the default system browser setting somewhere
    # if you are not root, you will get a "su" prompt that would misteriously
    # stall you
    if not os.getuid() == 0:
        return

    launch_chromium(args) 
Example #25
Source File: user.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def enforce_root(msg):
    if os.getuid() != 0:
        sys.stderr.write(msg.encode('utf-8') + "\n")
        sys.exit(1) 
Example #26
Source File: _checks.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def is_service_ready(provider):
    if not _has_valid_cert(provider):
        return False
    if os.getuid() == 0:
        # it's your problem if you run as root, not mine.
        return True
    if IS_LINUX and not is_pkexec_in_system():
        log.warn('System has no pkexec')
        return False
    return True 
Example #27
Source File: cwd.py    From NINJA-PingU with GNU General Public License v3.0 5 votes vote down vote up
def get_default_cwd():
    """Determine a reasonable default cwd"""
    cwd = os.getcwd()
    if not os.path.exists(cwd) or not os.path.isdir(cwd):
        try:
            cwd = pwd.getpwuid(os.getuid())[5]
        except KeyError:
            cwd = '/'
    
    return(cwd) 
Example #28
Source File: decorators.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def require_root(exit_on_failure=False, verbose=False):
    '''
    Generates decorator to enforce root permissions

    NB: must be called when used as decorator, i.e.
        @require_root()
        def my_func():
            pass

    @params  exit_on_failure   Quit application on failure
    @params  verbose           Print messages to stdout
    '''

    def require_root_decorator(func):
        '''
        Actual decorator that gets applied to functions
        '''

        @wraps(func)
        def ensure_root(*args, **kwargs):
            if os.getuid() != 0:
                msg = 'You need to run this option as root, try with sudo'
                logger.error(msg)

                if verbose:
                    sys.stdout.write('{}\n'.format(msg))

                if exit_on_failure:
                    sys.exit(ERR_ROOT_PERMISSIONS_REQ)

                return False

            return func(*args, **kwargs)

        return ensure_root

    return require_root_decorator 
Example #29
Source File: subprocess24.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno 
Example #30
Source File: _stdlib.py    From bugatsinho.github.io with GNU General Public License v3.0 5 votes vote down vote up
def _get_userdir(user=None):
    """Returns the user dir or None"""

    if user is not None and not isinstance(user, fsnative):
        raise TypeError

    if is_win:
        if "HOME" in environ:
            path = environ["HOME"]
        elif "USERPROFILE" in environ:
            path = environ["USERPROFILE"]
        elif "HOMEPATH" in environ and "HOMEDRIVE" in environ:
            path = os.path.join(environ["HOMEDRIVE"], environ["HOMEPATH"])
        else:
            return

        if user is None:
            return path
        else:
            return os.path.join(os.path.dirname(path), user)
    else:
        import pwd

        if user is None:
            if "HOME" in environ:
                return environ["HOME"]
            else:
                try:
                    return path2fsn(pwd.getpwuid(os.getuid()).pw_dir)
                except KeyError:
                    return
        else:
            try:
                return path2fsn(pwd.getpwnam(user).pw_dir)
            except KeyError:
                return