我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用pwd.getpwall()。
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
def main(self): users = pwd.getpwall() count = 0 for user in users: name = user.pw_name shell = user.pw_shell uid = user.pw_uid home_dir = user.pw_dir if (uid > 999 and self.isValidShell(shell)): if not self.isUserNameInDb(name): self.exitWithResult("User {} not defined by ansible".format(name)) else: self.checkUsersKeys(user) count = count + 1 result = {"changed": False, "msg": "Checked {} user accounts".format(count)} self.module.exit_json(**result)
def from_passwd(uid_min=None, uid_max=None): """Create collection from locally discovered data, e.g. /etc/passwd.""" import pwd users = Users(oktypes=User) passwd_list = pwd.getpwall() if not uid_min: uid_min = UID_MIN if not uid_max: uid_max = UID_MAX sudoers_entries = read_sudoers() for pwd_entry in passwd_list: if uid_min <= pwd_entry.pw_uid <= uid_max: user = User(name=text_type(pwd_entry.pw_name), passwd=text_type(pwd_entry.pw_passwd), uid=pwd_entry.pw_uid, gid=pwd_entry.pw_gid, gecos=text_type(pwd_entry.pw_gecos), home_dir=text_type(pwd_entry.pw_dir), shell=text_type(pwd_entry.pw_shell), public_keys=read_authorized_keys(username=pwd_entry.pw_name), sudoers_entry=get_sudoers_entry(username=pwd_entry.pw_name, sudoers_entries=sudoers_entries)) users.append(user) return users
def get_usernames_by_gid(gid, dirpath): if not already_called(): get_usernames_by_gid(gid, dirpath) try: load_passwd(dirpath) return [unam for unam, pwdentry in users[dirpath].items() if str(pwdentry.pw_gid) == gid ] except OSError as e: if e.errno != errno.ENOENT: raise # If the password file doesn't exist, bootstrap # ourselves from the current environment. # The following call could be expensive. allpwdentries = pwd.getpwall() if not allpwdentries: allpwdentries = [] return [ pwdentry.pw_name for pwdentry in allpwdentries if str(pwdentry.pw_gid) == gid ]
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
def nonsystem_users_exist(): '''Returns true if non-system accounts have been created.''' users_exist = False all_users_array = pwd.getpwall() for the_user in all_users_array: if int(the_user.pw_uid) > 500: users_exist = True break return users_exist
def user_exist(user): return user in map(lambda a: a.pw_name, pwd.getpwall())
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
def read_users_from_passwd(dirname="/etc"): """ Reads users from /etc/passwd, /etc/shadow (if it has access) and /etc/group """ pwds = pwd.getpwall() spwds = spwd.getspall() sn = {} for s in spwds: sn[s.sp_nam] = s users = {} for p in pwds: if p.pw_uid >= UID_MIN and p.pw_uid <= UID_MAX: if p.pw_name in sn: s = sn[p.pw_name] else: #print " * I couldn't find user %s in shadow file. Are you \ #root?" % p.pw_name s = spwd.struct_spwd(["", "x", "", "", "", "", "", "", ""]) rname, office, wphone, hphone = (p.pw_gecos + ",,,").split(",")[:4] u = User(p.pw_name, p.pw_uid, rname, office, wphone, hphone, p.pw_dir, p.pw_shell, [], s.sp_min, s.sp_max, s.sp_warn, s.sp_inact, s.sp_expire, s.sp_pwd, "") if u.inact == -1: u.inact = '' if u.expire == -1: u.expire = '' users[u.name] = u grps = grp.getgrall() for g in grps: for gu in g.gr_mem: if gu in users: users[gu].groups.append(g.gr_name) return sorted_users(users)
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])
def set_datadir_perms(): datadir = unitdata.kv().get('storage-path', False) if not datadir: # No juju storage attached, use defaults from package return users = [i for i in pwd.getpwall() if i.pw_name == 'nobody'] if len(users) == 1: os.lchown(datadir, users[0].pw_uid, users[0].pw_gid)
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 #----------------------------------------------------------------------
def _uid2usernames(self): d = collections.defaultdict(list) for u in pwd.getpwall(): d[u.pw_uid].append(u.pw_name) return d
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()]
def check_username(value): if value not in {x[0] for x in pwd.getpwall()}: raise ValueError('%s is not a valid user' % value) return value
def find_ssh_directories(): """ find_ssh_directories() -- Search pwents for home directories with .ssh directories. Scans each file in .ssh directory for valid SSH keys. Valid keys are added to VALID_KEYS list. Args: None Returns: True """ # TODO: search /home for orphaned home directories that may contain keys xprint("[+] Searching for SSH keys via valid pwents..") for pwent in pwd.getpwall(): user = pwent[0] sshdir = os.path.join(os.path.expanduser("~%s" % user), ".ssh") if os.path.isdir(sshdir): xprint("[*] Found .ssh directory for user %s: %s" % (user, sshdir)) for root, _, filenames in os.walk(sshdir): for filename in filenames: checkfile = os.path.join(root, filename) process_key(checkfile, user) xprint("") xprint("[+] %s usable %s discovered." % (len(VALID_KEYS), "keys" if len(VALID_KEYS) > 1 else "key")) return True
def list_user_homedir(): for p in pwd.getpwall(): if p[6] == '/bin/bash' and p[0] not in users_blacklist: users[p[0]] = p[5]