Python os.getuid() Examples

The following are code examples for showing how to use os.getuid(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: python-   Author: secondtonone1   File: site.py    (license) View Source Project 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 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 
Example 2
Project: my-first-blog   Author: AnkurBegining   File: site.py    (license) View Source Project 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 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 
Example 3
Project: HeaTDV4A   Author: HeaTTheatR   File: multipartform.py    (license) View Source Project 6 votes vote down vote up
def choose_boundary():
    global _prefix

    if _prefix is None:
        hostid = socket.gethostbyname(socket.gethostname())

        try:
            uid = `os.getuid()`
        except:
            uid = '1'
        try:
            pid = `os.getpid()`
        except:
            pid = '1'

        _prefix = hostid + '.' + uid + '.' + pid

    timestamp = '%.3f' % time.time()
    seed = `random.randint(0, 32767)`
    return _prefix + '.' + timestamp + '.' + seed 
Example 4
Project: kinect-2-libras   Author: inessadl   File: mimetools.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def choose_boundary():
    """Return a string usable as a multipart boundary.

    The string chosen is unique within a single program run, and
    incorporates the user id (if available), process id (if available),
    and current time.  So it's very unlikely the returned string appears
    in message text, but there's no guarantee.

    The boundary contains dots so you have to quote it in the header."""

    global _prefix
    import time
    if _prefix is None:
        import socket
        try:
            hostid = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            hostid = '127.0.0.1'
        try:
            uid = repr(os.getuid())
        except AttributeError:
            uid = '1'
        try:
            pid = repr(os.getpid())
        except AttributeError:
            pid = '1'
        _prefix = hostid + '.' + uid + '.' + pid
    return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())


# Subroutines for decoding some common content-transfer-types 
Example 5
Project: kinect-2-libras   Author: inessadl   File: site.py    (Apache License 2.0) View Source Project 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 6
Project: kinect-2-libras   Author: inessadl   File: getpass.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def getuser():
    """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.

    """

    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]

# Bind the name getpass to the appropriate function 
Example 7
Project: packagecore   Author: BytePackager   File: pkgbuild.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def prep(self, container):
        container.execute(["pacman", "-Syy", "--noconfirm", "sudo", "binutils",
                           "fakeroot"])
        uid = os.getuid()
        if uid == 0:
            # if we're running as root, make up a user
            uid = 1000
        container.execute(["useradd", "-m", "-u", str(uid), "packagecore"])
        container.execute(["/bin/bash", "-c",
                           "echo 'packagecore ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers"])
        # create our working directory
        self._pkgBuildDir = os.path.join(container.getSharedDir(),
                                         "arch-pkg")
        _makeDir(self._pkgBuildDir)

        self.generatePKGBUILDFile(container)

    ##
    # @brief Build the arch package.
    #
    # @param container The container to build in.
    #
    # @return None 
Example 8
Project: swjtu-pyscraper   Author: Desgard   File: site.py    (MIT License) View Source Project 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 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 
Example 9
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: site.py    (MIT License) View Source Project 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 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 
Example 10
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: site.py    (MIT License) View Source Project 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 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 
Example 11
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: site.py    (MIT License) View Source Project 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 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 
Example 12
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: site.py    (MIT License) View Source Project 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 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 
Example 13
Project: jira_worklog_scanner   Author: pgarneau   File: site.py    (license) View Source Project 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 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 
Example 14
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def t07(w):
    pretty = '%s t7' % __file__
    print(pretty)

    base = os.path.join(w.path, '.ave', 'config')
    os.makedirs(base)

    try:
        authkeys = ave.config.load_authkeys(w.path)
        print('FAIL %s: could load invalid config: %s' % (pretty, authkeys))
        return False
    except Exception, e:
        name = ave.pwd.getpwuid_name(os.getuid())
        if 'run "ave-config --bootstrap=%s"' % name not in unicode(e):
            print('FAIL %s: wrong error: %s' % (pretty, e))
            return False

    return True

# used by t8-t10. calls os._exit() so only use from within child process. 
Example 15
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def load(path):
    if not os.path.exists(path):
        user = ave.pwd.getpwuid_name(os.getuid())
        raise Exception(
            'no such configuration file: %s\n\nrun "ave-config --bootstrap=%s" '
            'to create one with default values' % (path, user)
        )

    config = None
    with open(path) as f:
        try:
            config = json.load(f)
        except Exception, e:
            raise Exception(
                'invalid config file %s: not valid JSON encoding: %s' % (path,e)
            )

    if type(config) != dict:
        raise Exception(
            'invalid config file %s: contents is not a dictionary: %s'
            % (path, type(config))
        )

    return config 
Example 16
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def t07(w):
    pretty = '%s t7' % __file__
    print(pretty)

    base = os.path.join(w.path, '.ave', 'config')
    os.makedirs(base)

    try:
        authkeys = ave.config.load_authkeys(w.path)
        print('FAIL %s: could load invalid config: %s' % (pretty, authkeys))
        return False
    except Exception, e:
        name = ave.pwd.getpwuid_name(os.getuid())
        if 'run "ave-config --bootstrap=%s"' % name not in unicode(e):
            print('FAIL %s: wrong error: %s' % (pretty, e))
            return False

    return True

# used by t8-t10. calls os._exit() so only use from within child process. 
Example 17
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def load(path):
    if not os.path.exists(path):
        user = ave.pwd.getpwuid_name(os.getuid())
        raise Exception(
            'no such configuration file: %s\n\nrun "ave-config --bootstrap=%s" '
            'to create one with default values' % (path, user)
        )

    config = None
    with open(path) as f:
        try:
            config = json.load(f)
        except Exception, e:
            raise Exception(
                'invalid config file %s: not valid JSON encoding: %s' % (path,e)
            )

    if type(config) != dict:
        raise Exception(
            'invalid config file %s: contents is not a dictionary: %s'
            % (path, type(config))
        )

    return config 
Example 18
Project: botany   Author: jifunks   File: botany.py    (license) View Source Project 6 votes vote down vote up
def init_database(self):
        # check if dir exists, create sqlite directory and set OS permissions to 777
        sqlite_dir_path = os.path.join(self.game_dir,'sqlite')
        if not os.path.exists(sqlite_dir_path):
            os.makedirs(sqlite_dir_path)
            os.chmod(sqlite_dir_path, 0777)
        conn = sqlite3.connect(self.garden_db_path)
        init_table_string = """CREATE TABLE IF NOT EXISTS garden (
        plant_id tinytext PRIMARY KEY,
        owner text,
        description text,
        age text,
        score integer,
        is_dead numeric
        )"""

        c = conn.cursor()
        c.execute(init_table_string)
        conn.close()

        # init only, creates and sets permissions for garden db and json
        if os.stat(self.garden_db_path).st_uid == os.getuid():
            os.chmod(self.garden_db_path, 0666)
            open(self.garden_json_path, 'a').close()
            os.chmod(self.garden_json_path, 0666) 
Example 19
Project: Wall-EEG   Author: neurotechuoft   File: elevate_admin.py    (license) View Source Project 6 votes vote down vote up
def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print("Admin check failed, assuming not an admin.")
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise(RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)) 
Example 20
Project: Static-UPnP   Author: nigelb   File: util.py    (license) View Source Project 6 votes vote down vote up
def drop_privileges(self, uid_name, gid_name):
    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        self.logger.info("Not running as root. Cannot drop permissions.")
        return

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    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(0o077)
    self.logger.info("Changed permissions to: %s: %i, %s, %i"%(uid_name, running_uid, gid_name, running_gid)) 
Example 21
Project: CodingDojo   Author: ComputerSocietyUNB   File: site.py    (license) View Source Project 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 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 
Example 22
Project: zanph   Author: zanph   File: site.py    (license) View Source Project 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 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 
Example 23
Project: hostapd-mana   Author: adde88   File: site.py    (license) View Source Project 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 24
Project: hostapd-mana   Author: adde88   File: unix.py    (license) View Source Project 6 votes vote down vote up
def startedConnecting(self, connector):
        fd = connector.transport.fileno()
        stats = os.fstat(fd)
        try:
            filestats = os.stat(connector.transport.addr)
        except:
            connector.stopConnecting()
            return
        if stat.S_IMODE(filestats[0]) != 0600:
            log.msg("socket mode is not 0600: %s" % oct(stat.S_IMODE(stats[0])))
        elif filestats[4] != os.getuid():
            log.msg("socket not owned by us: %s" % stats[4])
        elif filestats[5] != os.getgid():
            log.msg("socket not owned by our group: %s" % stats[5])
        # XXX reenable this when i can fix it for cygwin
        #elif filestats[-3:] != stats[-3:]:
        #    log.msg("socket doesn't have same create times")
        else:
            log.msg('conecting OK')
            return
        connector.stopConnecting() 
Example 25
Project: hostapd-mana   Author: adde88   File: getpass.py    (license) View Source Project 6 votes vote down vote up
def getuser():
    """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.

    """

    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]

# Bind the name getpass to the appropriate function 
Example 26
Project: hostapd-mana   Author: adde88   File: util.py    (license) View Source Project 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 27
Project: Bella   Author: Trietptm-on-Security   File: Bella.py    (license) View Source Project 6 votes vote down vote up
def is_there_SUID_shell():
	if os.getuid() == 0:
		return True

	if os.path.isfile('/usr/local/roots'):
		return True

	if local_pw_read():
		#send_msg("%sLocal PW present.\n" % greenPlus, False)
		binarymake = make_SUID_root_binary(local_pw_read(), None)
		#send_msg(binarymake[1], False)
		if binarymake[0]: #we have successfully created a temp root shell
			return True 
		return False

	return False 
Example 28
Project: Bella   Author: Trietptm-on-Security   File: Bella.py    (license) View Source Project 6 votes vote down vote up
def do_root(command):
	if os.getuid() == 0:
		output = subprocess.Popen("%s" % command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		out = output.stdout.read()
		err = output.stderr.read()
		if output.wait() != 0:
			return (False, '%sWe are root, but there was an error.\n%s%s' % (blue_star, yellow_star, err))
		return (True, "%s\n" % out)
	else:
		if not is_there_SUID_shell():
			return (False, '%sThere is no root shell to perform this command. See [rooter] manual entry.\n' % red_minus)
		output = subprocess.Popen("/usr/local/roots \"%s\"" % (command), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		out = output.stdout.read()
		err = output.stderr.read()
		if err != '':
			return (False, '%sThere is a root shell to perform this command, but there was an error.\n%s%s' % (blue_star, yellow_star, err))
		return (True, "%s\n" % out) 
Example 29
Project: Sci-Finder   Author: snverse   File: site.py    (license) View Source Project 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 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 
Example 30
Project: Sci-Finder   Author: snverse   File: site.py    (license) View Source Project 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 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 
Example 31
Project: Qyoutube-dl   Author: lzambella   File: compat.py    (license) View Source Project 6 votes vote down vote up
def compat_expanduser(path):
            """Expand ~ and ~user constructions.  If user or $HOME is unknown,
            do nothing."""
            if not path.startswith('~'):
                return path
            i = path.find('/', 1)
            if i < 0:
                i = len(path)
            if i == 1:
                if 'HOME' not in os.environ:
                    import pwd
                    userhome = pwd.getpwuid(os.getuid()).pw_dir
                else:
                    userhome = compat_getenv('HOME')
            else:
                import pwd
                try:
                    pwent = pwd.getpwnam(path[1:i])
                except KeyError:
                    return path
                userhome = pwent.pw_dir
            userhome = userhome.rstrip('/')
            return (userhome + path[i:]) or '/' 
Example 32
Project: national-geographic-wallpaper   Author: atareao   File: croni.py    (license) View Source Project 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 = '{0};{1};{2} {3} && {4}'.format(SLEEP, params,
                                                           EXEC, SCRIPT, gset)
        else:
            self.command = None 
Example 33
Project: civet   Author: TheJacksonLaboratory   File: validity_thorough_unused.py    (license) View Source Project 6 votes vote down vote up
def effectivelyReadable(self):
        uid = os.getuid()
        euid = os.geteuid()
        gid = os.getgid()
        egid = os.getegid()

        # This is probably true most of the time, so just let os.access()
        # handle it.  Avoids potential bugs in the rest of this function.
        if uid == euid and gid == egid:
            return os.access(self.name, os.R_OK)

        st = os.stat(self.name)

        # This may be wrong depending on the semantics of your OS.
        # i.e. if the file is -------r--, does the owner have access or not?
        if st.st_uid == euid:
            return st.st_mode & stat.S_IRUSR != 0

        # See comment for UID check above.
        groups = os.getgroups()
        if st.st_gid == egid or st.st_gid in groups:
            return st.st_mode & stat.S_IRGRP != 0

        return st.st_mode & stat.S_IROTH != 0 
Example 34
Project: civet   Author: TheJacksonLaboratory   File: validity.py    (license) View Source Project 6 votes vote down vote up
def effectivelyReadable(self):
        uid = os.getuid()
        euid = os.geteuid()
        gid = os.getgid()
        egid = os.getegid()

        # This is probably true most of the time, so just let os.access()
        # handle it.  Avoids potential bugs in the rest of this function.
        if uid == euid and gid == egid:
            return os.access(self.name, os.R_OK)

        st = os.stat(self.name)

        # This may be wrong depending on the semantics of your OS.
        # i.e. if the file is -------r--, does the owner have access or not?
        if st.st_uid == euid:
            return st.st_mode & stat.S_IRUSR != 0

        # See comment for UID check above.
        groups = os.getgroups()
        if st.st_gid == egid or st.st_gid in groups:
            return st.st_mode & stat.S_IRGRP != 0

        return st.st_mode & stat.S_IROTH != 0 
Example 35
Project: ascii-art-py   Author: blinglnav   File: site.py    (license) View Source Project 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 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 
Example 36
Project: Scrum   Author: prakharchoudhary   File: site.py    (license) View Source Project 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 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 
Example 37
Project: uac-a-mola   Author: ElevenPaths   File: admin.py    (license) View Source Project 6 votes vote down vote up
def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print "Admin check failed, assuming not an admin."
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise RuntimeError, "Unsupported operating system for this module: %s" % (
            os.name,) 
Example 38
Project: cheribuild   Author: CTSRD-CHERI   File: cheribsd.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, config: CheriConfig):
        self.installAsRoot = os.getuid() == 0
        self.cheriCXX = self.cheriCC.parent / "clang++"
        archBuildFlags = {
            "CHERI":config.cheriBitsStr,
            "CHERI_CC":str(self.cheriCC),
            "CHERI_CXX":str(self.cheriCXX),
            "CHERI_LD":str(config.sdkBinDir / "ld.lld"),
            "TARGET": "mips",
            "TARGET_ARCH": "mips64"
        }
        if self.mipsOnly:
            archBuildFlags = {"TARGET":"mips", "TARGET_ARCH":"mips64", "WITHOUT_LIB32": True}
            # keep building a cheri kernel even with a mips userspace (mips may be broken...)
            # self.kernelConfig = "MALTA64"
        super().__init__(config, archBuildFlags=archBuildFlags) 
Example 39
Project: ivaochdoc   Author: ivaoch   File: site.py    (license) View Source Project 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 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 
Example 40
Project: new   Author: atlj   File: sysinfo.py    (license) View Source Project 6 votes vote down vote up
def getos():
    dagitim=platform.dist()
    dagitim=dagitim[0]
    mimari=platform.machine()
    osys=platform.system()
    unumber = os.getuid()
    zaman=time.ctime()
    if unumber==0:
        kulanici="root"
    else:
        kulanici="No root"
    
    
    bilgi="""
        ============================
        CPU: {}
        OS: {}
        DAGITIM: {}
        KULANICI: {}
        ZAMAN: {}
       ============================""".format(mimari,osys,dagitim,kulanici,zaman)
    print(bilgi) 
Example 41
Project: crypto-detector   Author: Wind-River   File: rpm.py    (license) View Source Project 6 votes vote down vote up
def chown(self, cpioinfo, cpiogetpath):
        """Set owner of cpiogetpath according to cpioinfo.
        """
        if PWD and hasattr(os, "geteuid") and os.geteuid() == 0:
            # We have to be root to do so.
            try:
                g = GRP.getgrgid(cpioinfo.gid)[2]
            except KeyError:
                g = os.getgid()
            try:
                u = PWD.getpwuid(cpioinfo.uid)[2]
            except KeyError:
                u = os.getuid()
            try:
                if cpioinfo.issym() and hasattr(os, "lchown"):
                    os.lchown(cpiogetpath, u, g)
                else:
                    if sys.platform != "os2emx":
                        os.chown(cpiogetpath, u, g)
            except EnvironmentError:
                raise ExtractError("could not change owner") 
Example 42
Project: django   Author: alexsukhrin   File: site.py    (license) View Source Project 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 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 
Example 43
Project: BoopSuite   Author: MisterBianco   File: arguments.py    (license) View Source Project 6 votes vote down vote up
def root_check():
    # Check for root.
    if os.getuid() != 0:

        print("User is not Root.")
        sys.exit(103)

    if "linux" not in sys.platform.lower():

        print("Wrong OS.")
        sys.exit(104)

    return 0


# Handler for ctrl+c Event. 
Example 44
Project: RPoint   Author: george17-meet   File: site.py    (license) View Source Project 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 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 
Example 45
Project: isni-reconcile   Author: cmh2166   File: site.py    (license) View Source Project 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 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 
Example 46
Project: youtube_downloader   Author: aksinghdce   File: compat.py    (license) View Source Project 6 votes vote down vote up
def compat_expanduser(path):
            """Expand ~ and ~user constructions.  If user or $HOME is unknown,
            do nothing."""
            if not path.startswith('~'):
                return path
            i = path.find('/', 1)
            if i < 0:
                i = len(path)
            if i == 1:
                if 'HOME' not in os.environ:
                    import pwd
                    userhome = pwd.getpwuid(os.getuid()).pw_dir
                else:
                    userhome = compat_getenv('HOME')
            else:
                import pwd
                try:
                    pwent = pwd.getpwnam(path[1:i])
                except KeyError:
                    return path
                userhome = pwent.pw_dir
            userhome = userhome.rstrip('/')
            return (userhome + path[i:]) or '/' 
Example 47
Project: habilitacion   Author: GabrielBD   File: site.py    (license) View Source Project 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 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 
Example 48
Project: Intranet-Penetration   Author: yuxiaokui   File: site.py    (license) View Source Project 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 49
Project: Intranet-Penetration   Author: yuxiaokui   File: getpass.py    (license) View Source Project 6 votes vote down vote up
def getuser():
    """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.

    """

    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]

# Bind the name getpass to the appropriate function 
Example 50
Project: flasky   Author: RoseOu   File: site.py    (license) View Source Project 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 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