Python pwd.getpwall() Examples

The following are 30 code examples of pwd.getpwall(). 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: registration.py    From ahenk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def enable_local_users(self):
        passwd_cmd = 'passwd -u {}'
        change_home = 'usermod -m -d {0} {1}'
        change_username = 'usermod -l {0} {1}'
        content = self.util.read_file('/etc/passwd')
        for p in pwd.getpwall():
            if not sysx.shell_is_interactive(p.pw_shell):
                continue
            if p.pw_uid == 0:
                continue
            if p.pw_name in content:
                new_home_dir = p.pw_dir.rstrip('-local/') + '/'
                new_username = p.pw_name.rstrip('-local')
                self.util.execute(passwd_cmd.format(p.pw_name))
                self.util.execute(change_username.format(new_username, p.pw_name))
                self.util.execute(change_home.format(new_home_dir, new_username))
                self.logger.debug("User: '{0}' will be enabled and changed username and home directory of username".format(p.pw_name)) 
Example #2
Source File: registration.py    From ahenk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def enable_local_users(self):
        passwd_cmd = 'passwd -u {}'
        change_home = 'usermod -m -d {0} {1}'
        change_username = 'usermod -l {0} {1}'
        content = self.util.read_file('/etc/passwd')
        for p in pwd.getpwall():
            if not sysx.shell_is_interactive(p.pw_shell):
                continue
            if p.pw_uid == 0:
                continue
            if p.pw_name in content:
                new_home_dir = p.pw_dir.rstrip('-local/') + '/'
                new_username = p.pw_name.rstrip('-local')
                self.util.execute(passwd_cmd.format(p.pw_name))
                self.util.execute(change_username.format(new_username, p.pw_name))
                self.util.execute(change_home.format(new_home_dir, new_username))
                self.logger.debug("User: '{0}' will be enabled and changed username and home directory of username".format(p.pw_name)) 
Example #3
Source File: users.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def get_system(uid=None):
    """
    Get all system users.

    :param str id: ID of single user to fetch
    :param str name: username of single user to fetch
    :returns: SystemUser(s)
    :rtype: SystemUser or list thereof
    """
    r = []
    grps = groups.get_system()
    for x in pwd.getpwall():
        if x.pw_name == "root":
            continue
        su = SystemUser(name=x.pw_name, uid=x.pw_uid)
        for y in grps:
            if su.name in y.users:
                su.groups.append(y.name)
        if uid == su.name:
            return su
        r.append(su)
    return sorted(r, key=lambda x: x.uid) if not uid else None 
Example #4
Source File: tmetadata.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def test_restore_nonexistent_user_group():
    tmpdir = tempfile.mkdtemp(prefix='bup-tmetadata-')
    try:
        path = tmpdir + '/foo'
        os.mkdir(path)
        m = metadata.from_path(path, archive_path=path, save_symlinks=True)
        WVPASSEQ(m.path, path)
        junk,m.owner = max([(len(x.pw_name), x.pw_name + 'x')
        		    for x in pwd.getpwall()])
        junk,m.group = max([(len(x.gr_name), x.gr_name + 'x')
                            for x in grp.getgrall()])
        WVPASSEQ(m.apply_to_path(path, restore_numeric_ids=True), None)
        WVPASSEQ(os.stat(path).st_uid, m.uid)
        WVPASSEQ(os.stat(path).st_gid, m.gid)
        WVPASSEQ(m.apply_to_path(path, restore_numeric_ids=False), None)
        WVPASSEQ(os.stat(path).st_uid, m.uid)
        WVPASSEQ(os.stat(path).st_gid, m.gid)
    finally:
        subprocess.call(['rm', '-rf', tmpdir]) 
Example #5
Source File: distrib.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def wmfactory_directory(self, request):
        m = []
        for user in pwd.getpwall():
            pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                     = user
            realname = string.split(pw_gecos,',')[0]
            if not realname:
                realname = pw_name
            if os.path.exists(os.path.join(pw_dir, self.userDirName)):
                m.append({
                        'href':'%s/'%pw_name,
                        'text':'%s (file)'%realname
                })
            twistdsock = os.path.join(pw_dir, self.userSocketName)
            if os.path.exists(twistdsock):
                linknm = '%s.twistd' % pw_name
                m.append({
                        'href':'%s/'%linknm,
                        'text':'%s (twistd)'%realname})
        return m 
Example #6
Source File: authorizers.py    From pyftpdlib with MIT License 5 votes vote down vote up
def _get_system_users():
            """Return all users defined on the UNIX system."""
            # there should be no need to convert usernames to unicode
            # as UNIX does not allow chars outside of ASCII set
            return [entry.pw_name for entry in pwd.getpwall()] 
Example #7
Source File: CGIHTTPServer.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #8
Source File: CGIHTTPServer.py    From canape with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #9
Source File: server.py    From android_universal with MIT License 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #10
Source File: CGIHTTPServer.py    From unity-python with MIT License 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #11
Source File: CGIHTTPServer.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #12
Source File: server.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #13
Source File: test_contracts.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        if POSIX:
            import pwd
            import grp
            users = pwd.getpwall()
            groups = grp.getgrall()
            self.all_uids = set([x.pw_uid for x in users])
            self.all_usernames = set([x.pw_name for x in users])
            self.all_gids = set([x.gr_gid for x in groups]) 
Example #14
Source File: CGIHTTPServer.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #15
Source File: top.py    From python-scripts with GNU General Public License v3.0 5 votes vote down vote up
def get_all_user():
    """ get user of system """
    import pwd

    all_user = {}
    for user in pwd.getpwall():
        all_user[user[0]] = all_user[user[2]] = user

    return all_user 
Example #16
Source File: server.py    From gimp-plugin-export-layers with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #17
Source File: CGIHTTPServer.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #18
Source File: server.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #19
Source File: CGIHTTPServer.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #20
Source File: httpserver.py    From febrev-venom with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #21
Source File: CGIHTTPServer.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #22
Source File: macos_user.py    From stonix with GNU General Public License v2.0 5 votes vote down vote up
def getUsers(self):
        '''Return a list of users, from pwd.
        
        Password database entries are reported as a tuple-like object, whose
        attributes correspond to the members of the passwd structure (Attribute
        field below, see <pwd.h>):
        
        Index    Attribute    Meaning
        0    pw_name    Login name
        1    pw_passwd    Optional encrypted password
        2    pw_uid    Numerical user ID
        3    pw_gid    Numerical group ID
        4    pw_gecos    User name or comment field
        5    pw_dir    User home directory
        6    pw_shell    User command interpreter
        
        The uid and gid items are integers, all others are strings. KeyError
        is raised if the entry asked for cannot be found.


        '''
        self.users = pwd.getpwall()
        return self.users
        
    #----------------------------------------------------------------------
    # Getters
    #---------------------------------------------------------------------- 
Example #23
Source File: RemoveBadDotFiles.py    From stonix with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, config, environ, logger, statechglogger):
        '''
        Constructor
        '''
        Rule.__init__(self, config, environ, logger, statechglogger)
        self.config = config
        self.environ = environ
        self.logger = logger
        self.statechglogger = statechglogger
        self.rulenumber = 47
        self.rulename = 'RemoveBadDotFiles'
        self.formatDetailedResults("initialize")
        self.mandatory = True
        self.sethelptext()
        self.rootrequired = False
        datatype = 'bool'
        key = 'REMOVEBADDOTFILES'
        instructions = "To disable this rule set the value of " + \
        "REMOVEBADDOTFILES to False"
        default = True
        self.nonetrc = self.initCi(datatype, key, instructions, default)
        self.guidance = ['NSA 2.3.4.5', 'cce-4578-1']
        self.applicable = {'type': 'white',
                           'family': ['linux', 'solaris', 'freebsd'],
                           'os': {'Mac OS X': ['10.15', 'r', '10.15.10']}}
        self.homelist = ['/', '/root']
        try:
            mypwd = pwd.getpwall()
            for user in mypwd:
                home = user[5]
                if home not in self.homelist:
                    self.homelist.append(home)
            if self.environ.geteuid() != 0:
                pwdsingle = pwd.getpwuid(self.environ.geteuid())
                self.homelist = pwdsingle[5]
        except(IndexError, OSError):
            pass 
Example #24
Source File: test_pwd.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_values(self):
        entries = pwd.getpwall()
        entriesbyname = {}
        entriesbyuid = {}

        for e in entries:
            self.assertEqual(len(e), 7)
            self.assertEqual(e[0], e.pw_name)
            self.assert_(isinstance(e.pw_name, basestring))
            self.assertEqual(e[1], e.pw_passwd)
            self.assert_(isinstance(e.pw_passwd, basestring))
            self.assertEqual(e[2], e.pw_uid)
            self.assert_(isinstance(e.pw_uid, int))
            self.assertEqual(e[3], e.pw_gid)
            self.assert_(isinstance(e.pw_gid, int))
            self.assertEqual(e[4], e.pw_gecos)
            self.assert_(isinstance(e.pw_gecos, basestring))
            self.assertEqual(e[5], e.pw_dir)
            self.assert_(isinstance(e.pw_dir, basestring))
            self.assertEqual(e[6], e.pw_shell)
            self.assert_(isinstance(e.pw_shell, basestring))

            # The following won't work, because of duplicate entries
            # for one uid
            #    self.assertEqual(pwd.getpwuid(e.pw_uid), e)
            # instead of this collect all entries for one uid
            # and check afterwards
            entriesbyname.setdefault(e.pw_name, []).append(e)
            entriesbyuid.setdefault(e.pw_uid, []).append(e)

        if len(entries) > 1000:  # Huge passwd file (NIS?) -- skip the rest
            return

        # check whether the entry returned by getpwuid()
        # for each uid is among those from getpwall() for this uid
        for e in entries:
            if not e[0] or e[0] == '+':
                continue # skip NIS entries etc.
            self.assert_(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name])
            self.assert_(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid]) 
Example #25
Source File: CGIHTTPServer.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #26
Source File: test_pathlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_expanduser(self):
        P = self.cls
        support.import_module('pwd')
        import pwd
        pwdent = pwd.getpwuid(os.getuid())
        username = pwdent.pw_name
        userhome = pwdent.pw_dir.rstrip('/') or '/'
        # find arbitrary different user (if exists)
        for pwdent in pwd.getpwall():
            othername = pwdent.pw_name
            otherhome = pwdent.pw_dir.rstrip('/')
            if othername != username and otherhome:
                break

        p1 = P('~/Documents')
        p2 = P('~' + username + '/Documents')
        p3 = P('~' + othername + '/Documents')
        p4 = P('../~' + username + '/Documents')
        p5 = P('/~' + username + '/Documents')
        p6 = P('')
        p7 = P('~fakeuser/Documents')

        with support.EnvironmentVarGuard() as env:
            env.pop('HOME', None)

            self.assertEqual(p1.expanduser(), P(userhome) / 'Documents')
            self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
            self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
            self.assertEqual(p4.expanduser(), p4)
            self.assertEqual(p5.expanduser(), p5)
            self.assertEqual(p6.expanduser(), p6)
            self.assertRaises(RuntimeError, p7.expanduser)

            env['HOME'] = '/tmp'
            self.assertEqual(p1.expanduser(), P('/tmp/Documents'))
            self.assertEqual(p2.expanduser(), P(userhome) / 'Documents')
            self.assertEqual(p3.expanduser(), P(otherhome) / 'Documents')
            self.assertEqual(p4.expanduser(), p4)
            self.assertEqual(p5.expanduser(), p5)
            self.assertEqual(p6.expanduser(), p6)
            self.assertRaises(RuntimeError, p7.expanduser) 
Example #27
Source File: server.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #28
Source File: CGIHTTPServer.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
    return nobody 
Example #29
Source File: server.py    From blackmamba with MIT License 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody 
Example #30
Source File: server.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def nobody_uid():
    """Internal routine to get nobody's uid"""
    global nobody
    if nobody:
        return nobody
    try:
        import pwd
    except ImportError:
        return -1
    try:
        nobody = pwd.getpwnam('nobody')[2]
    except KeyError:
        nobody = 1 + max(x[2] for x in pwd.getpwall())
    return nobody