Python pwd.getpwuid() Examples

The following are 30 code examples of pwd.getpwuid(). 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 pwd , or try the search function .
Example #1
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 #2
Source File: test_shutil.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = _make_tarball(base_name, 'dist', compress=None,
                                         owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example #3
Source File: clam_av_run.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def open_file(s):
       with open(s,'r') as f:
               f.next()
               f.next()
               f.next()
               for line in f:
                       if "FOUND" in line:
                               x = line.split(':')
                               file_paths.append(x[0])
       if len(file_paths) == 0:
               print {}
               return
       for p in file_paths:
               filename = p
               get_time = os.path.getctime(p)
               format_time = datetime.fromtimestamp(get_time).strftime('%Y-%m-%d %H:%M:%S')
               hashvalue = hashlib.sha1(filename).hexdigest()
               owner_name = getpwuid(stat(filename).st_uid).pw_name
               json_output["malicious_files"].append({"file":p, "owner":owner_name, "hash_value":hashvalue, "time_created":format_time})

       print json.dumps(json_output)

# Scan the directory 
Example #4
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 #5
Source File: test_archive_util.py    From Computable with MIT License 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = make_tarball(base_name, 'dist', compress=None,
                                        owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example #6
Source File: test_archive_util.py    From Computable with MIT License 6 votes vote down vote up
def test_make_archive_owner_group(self):
        # testing make_archive with owner and group, with various combinations
        # this works even if there's not gid/uid support
        if UID_GID_SUPPORT:
            group = grp.getgrgid(0)[0]
            owner = pwd.getpwuid(0)[0]
        else:
            group = owner = 'root'

        base_dir, root_dir, base_name =  self._create_files()
        base_name = os.path.join(self.mkdtemp() , 'archive')
        res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
                           group=group)
        self.assertTrue(os.path.exists(res))

        res = make_archive(base_name, 'zip', root_dir, base_dir)
        self.assertTrue(os.path.exists(res))

        res = make_archive(base_name, 'tar', root_dir, base_dir,
                           owner=owner, group=group)
        self.assertTrue(os.path.exists(res))

        res = make_archive(base_name, 'tar', root_dir, base_dir,
                           owner='kjhkjhkjg', group='oihohoh')
        self.assertTrue(os.path.exists(res)) 
Example #7
Source File: util.py    From Computable 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 #8
Source File: _path.py    From Computable with MIT License 6 votes vote down vote up
def get_owner(self):
        r""" Return the name of the owner of this file or directory.

        This follows symbolic links.

        On Windows, this returns a name of the form ur'DOMAIN\User Name'.
        On Windows, a group can own a file or directory.
        """
        if os.name == 'nt':
            if win32security is None:
                raise Exception("path.owner requires win32all to be installed")
            desc = win32security.GetFileSecurity(
                self, win32security.OWNER_SECURITY_INFORMATION)
            sid = desc.GetSecurityDescriptorOwner()
            account, domain, typecode = win32security.LookupAccountSid(None, sid)
            return domain + u'\\' + account
        else:
            if pwd is None:
                raise NotImplementedError("path.owner is not implemented on this platform.")
            st = self.stat()
            return pwd.getpwuid(st.st_uid).pw_name 
Example #9
Source File: cred.py    From magpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getuser():
    sysuser = os.getenv("USER")
    # if sysuser could not be identified try Logname
    if sysuser == None:
        print("Getuser: Running from crontab -- trying Logname to identify user")
        try:
            sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
        except:
            sysuser = None
        if not sysuser == None:
            print("Getuser: ... succes - using", sysuser)
    # if sysuser still could not be identified assume that uid 1000 is the defaultuser (on linux)
    if sysuser == None or sysuser == 'None':
        print("Getuser: Cannot identify user by standard procedures - switching to default uid 1000")
        sysuser = pwd.getpwuid(1000)[0]
        print("Getuser: now using", sysuser)
    return sysuser
    # path to home directory
    #if os.isatty(sys.stdin.fileno()):
    #    sysuser = os.getenv("USER")
    #    pass
    #else:
    #    sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
    #    pass 
Example #10
Source File: topology.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
def netstat_tcp6():
    '''
    This function returns a list of tcp connections utilizing ipv6. Please note that in order to return the pid of of a
    network process running on the system, this script must be ran as root.
    '''
    tcpcontent = _tcp6load()
    tcpresult = []
    for line in tcpcontent:
        line_array = _remove_empty(line.split(' '))
        l_host, l_port = _convert_ipv6_port(line_array[1])
        r_host, r_port = _convert_ipv6_port(line_array[2])
        tcp_id = line_array[0]
        state = TCP_STATE[line_array[3]]
        uid = pwd.getpwuid(int(line_array[7]))[0]
        inode = line_array[9]
        pid = _get_pid_of_inode(inode)
        try:                                            # try read the process name.
            exe = os.readlink('/proc/' + pid + '/exe')
        except:
            exe = None

        nline = [tcp_id, uid, l_host + ':' + l_port,
                 r_host + ':' + r_port, state, pid, exe]
        tcpresult.append(nline)
    return tcpresult 
Example #11
Source File: getpass.py    From BinderFilter with MIT License 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 #12
Source File: webbrowser.py    From BinderFilter 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 #13
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 #14
Source File: __init__.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def username(self):
        """The name of the user that owns the process.
        On UNIX this is calculated by using *real* process uid.
        """
        if POSIX:
            if pwd is None:
                # might happen if python was installed from sources
                raise ImportError(
                    "requires pwd module shipped with standard python")
            real_uid = self.uids().real
            try:
                return pwd.getpwuid(real_uid).pw_name
            except KeyError:
                # the uid can't be resolved by the system
                return str(real_uid)
        else:
            return self._proc.username() 
Example #15
Source File: pcap_dump.py    From QCSuper with GNU General Public License v3.0 6 votes vote down vote up
def detach_process(self):
        
        # Don't be hit by CTRL+C
        
        setpgrp()
        
        # Drop privileges if needed
        
        uid, gid = getenv('SUDO_UID'), getenv('SUDO_GID')
        
        if uid and gid:
            
            uid, gid = int(uid), int(gid)

            setgroups(getgrouplist(getpwuid(uid).pw_name, gid))

            setresgid(gid, gid, -1)
            
            setresuid(uid, uid, -1) 
Example #16
Source File: util.py    From BinderFilter 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 #17
Source File: sysvalidator.py    From upvm with Apache License 2.0 6 votes vote down vote up
def check_for_writable_imgdir():
    c.debug("Testing write perms by creating tempfile in {}".format(cfg.opts.img_dir))
    try:
        f = tempfile.TemporaryFile(dir=cfg.opts.img_dir)
        f.close()
    except:
        dirstat = os.stat(cfg.opts.img_dir)
        user = pwd.getpwuid(dirstat.st_uid).pw_name
        group = grp.getgrgid(dirstat.st_gid).gr_name
        print(c.RED("Unable to create new file in image dir '{}' owned by {}:{}".format(cfg.opts.img_dir, user, group)))
        if myUser in grp.getgrnam(group).gr_mem:
            print("Your user ({}) *is* a member of the appropriate group ({}); however ...\n"
                  "Your current login session is not running with that group credential\n"
                  "To fix this, open a new session (ssh/su -) or log out & log back in (GUI)".format(myUser, group))
        else:
            print("Either fix directory permissions as root or specify alternate dir with '--img-dir' option")
        exit(1) 
Example #18
Source File: __init__.py    From dpa-pipe with MIT License 6 votes vote down vote up
def current_username():
    """Retrieve the username of the current user.

    :rtype: str
    :return: The username of the current user.
 
    >>> from dpa.user import current_username
    >>> username = current_username()
    >>> print username
    'jtomlin'

    """ 

    # see this StackOverflow thread for a discussion on a portable way to 
    # get the current user name: http://tinyurl.com/ykecvzc
    if pwd:
        return pwd.getpwuid(os.geteuid()).pw_name
    else:
        return getpass.getuser()

# -----------------------------------------------------------------------------
# Public Classes:
# ----------------------------------------------------------------------------- 
Example #19
Source File: __init__.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def username(self):
        """The name of the user that owns the process.
        On UNIX this is calculated by using *real* process uid.
        """
        if POSIX:
            if pwd is None:
                # might happen if python was installed from sources
                raise ImportError(
                    "requires pwd module shipped with standard python")
            real_uid = self.uids().real
            try:
                return pwd.getpwuid(real_uid).pw_name
            except KeyError:
                # the uid can't be resolved by the system
                return str(real_uid)
        else:
            return self._proc.username() 
Example #20
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 #21
Source File: test_posix.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_initgroups(self):
        # It takes a string and an integer; check that it raises a TypeError
        # for other argument lists.
        self.assertRaises(TypeError, posix.initgroups)
        self.assertRaises(TypeError, posix.initgroups, None)
        self.assertRaises(TypeError, posix.initgroups, 3, "foo")
        self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())

        # If a non-privileged user invokes it, it should fail with OSError
        # EPERM.
        if os.getuid() != 0:
            try:
                name = pwd.getpwuid(posix.getuid()).pw_name
            except KeyError:
                # the current UID may not have a pwd entry
                raise unittest.SkipTest("need a pwd entry")
            try:
                posix.initgroups(name, 13)
            except OSError as e:
                self.assertEqual(e.errno, errno.EPERM)
            else:
                self.fail("Expected OSError to be raised by initgroups") 
Example #22
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 #23
Source File: getpass.py    From meddle with MIT License 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 #24
Source File: test_shutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_tarfile_root_owner(self):
        root_dir, base_dir = self._create_files()
        base_name = os.path.join(self.mkdtemp(), 'archive')
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        with support.change_cwd(root_dir):
            archive_name = make_archive(base_name, 'gztar', root_dir, 'dist',
                                        owner=owner, group=group)

        # check if the compressed tarball was created
        self.assertTrue(os.path.isfile(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example #25
Source File: util.py    From ironpython2 with Apache License 2.0 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:
        try:
            import pwd
            os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
        except (ImportError, KeyError):
            # bpo-10496: if the current user identifier doesn't exist in the
            # password database, do nothing
            pass

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

    _environ_checked = 1 
Example #26
Source File: test_util.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_check_environ_getpwuid(self):
        util._environ_checked = 0
        os.environ.pop('HOME', None)

        import pwd

        # only set pw_dir field, other fields are not used
        def mock_getpwuid(uid):
            return pwd.struct_passwd((None, None, None, None, None,
                                      '/home/distutils', None))

        with swap_attr(pwd, 'getpwuid', mock_getpwuid):
            check_environ()
            self.assertEqual(os.environ['HOME'], '/home/distutils')

        util._environ_checked = 0
        os.environ.pop('HOME', None)

        # bpo-10496: Catch pwd.getpwuid() error
        def getpwuid_err(uid):
            raise KeyError
        with swap_attr(pwd, 'getpwuid', getpwuid_err):
            check_environ()
            self.assertNotIn('HOME', os.environ) 
Example #27
Source File: test_shutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_make_archive_owner_group(self):
        # testing make_archive with owner and group, with various combinations
        # this works even if there's not gid/uid support
        if UID_GID_SUPPORT:
            group = grp.getgrgid(0)[0]
            owner = pwd.getpwuid(0)[0]
        else:
            group = owner = 'root'

        root_dir, base_dir = self._create_files()
        base_name = os.path.join(self.mkdtemp(), 'archive')
        res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
                           group=group)
        self.assertTrue(os.path.isfile(res))

        res = make_archive(base_name, 'zip', root_dir, base_dir)
        self.assertTrue(os.path.isfile(res))

        res = make_archive(base_name, 'tar', root_dir, base_dir,
                           owner=owner, group=group)
        self.assertTrue(os.path.isfile(res))

        res = make_archive(base_name, 'tar', root_dir, base_dir,
                           owner='kjhkjhkjg', group='oihohoh')
        self.assertTrue(os.path.isfile(res)) 
Example #28
Source File: test_archive_util.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_make_archive_owner_group(self):
        # testing make_archive with owner and group, with various combinations
        # this works even if there's not gid/uid support
        if UID_GID_SUPPORT:
            group = grp.getgrgid(0)[0]
            owner = pwd.getpwuid(0)[0]
        else:
            group = owner = 'root'

        base_dir, root_dir, base_name =  self._create_files()
        base_name = os.path.join(self.mkdtemp() , 'archive')
        res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
                           group=group)
        self.assertTrue(os.path.exists(res))

        res = make_archive(base_name, 'zip', root_dir, base_dir)
        self.assertTrue(os.path.exists(res))

        res = make_archive(base_name, 'tar', root_dir, base_dir,
                           owner=owner, group=group)
        self.assertTrue(os.path.exists(res))

        res = make_archive(base_name, 'tar', root_dir, base_dir,
                           owner='kjhkjhkjg', group='oihohoh')
        self.assertTrue(os.path.exists(res)) 
Example #29
Source File: test_archive_util.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = make_tarball(base_name, 'dist', compress=None,
                                        owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example #30
Source File: getpass.py    From ironpython2 with Apache License 2.0 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