我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用grp.getgrnam()。
def mkdir(path, owner='root', group='root', perms=0o555, force=False): """Create a directory""" log("Making dir {} {}:{} {:o}".format(path, owner, group, perms)) uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid realpath = os.path.abspath(path) path_exists = os.path.exists(realpath) if path_exists and force: if not os.path.isdir(realpath): log("Removing non-directory file {} prior to mkdir()".format(path)) os.unlink(realpath) os.makedirs(realpath, perms) elif not path_exists: os.makedirs(realpath, perms) os.chown(realpath, uid, gid) os.chmod(realpath, perms)
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError as e: raise ExtractError("could not change owner")
def _dropPrivileges(self, user, group): import pwd, grp # Get the uid/gid from the name runningUid = pwd.getpwnam(user).pw_uid runningGid = grp.getgrnam(group).gr_gid # Remove group privileges os.setgroups([]) # Try setting the new uid/gid os.setgid(runningGid) os.setuid(runningUid) # Reset logging self.resetLogging()
def add_group(group_name, system_group=False): """Add a group to the system""" try: group_info = grp.getgrnam(group_name) log('group {0} already exists!'.format(group_name)) except KeyError: log('creating group {0}'.format(group_name)) cmd = ['addgroup'] if system_group: cmd.append('--system') else: cmd.extend([ '--group', ]) cmd.append(group_name) subprocess.check_call(cmd) group_info = grp.getgrnam(group_name) return group_info
def add_group(group_name, system_group=False, gid=None): """Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam` """ try: group_info = grp.getgrnam(group_name) log('group {0} already exists!'.format(group_name)) if gid: group_info = grp.getgrgid(gid) log('group with gid {0} already exists!'.format(gid)) except KeyError: log('creating group {0}'.format(group_name)) add_new_group(group_name, system_group, gid) group_info = grp.getgrnam(group_name) return group_info
def default(): """ Remove the .../stack/defaults directory. Preserve available_roles """ # Keep yaml human readable/editable friendly_dumper = yaml.SafeDumper friendly_dumper.ignore_aliases = lambda self, data: True preserve = {} content = None pathname = "/srv/pillar/ceph/stack/default/{}/cluster.yml".format('ceph') with open(pathname, "r") as sls_file: content = yaml.safe_load(sls_file) preserve['available_roles'] = content['available_roles'] stack_default = "/srv/pillar/ceph/stack/default" shutil.rmtree(stack_default) os.makedirs("{}/{}".format(stack_default, 'ceph')) with open(pathname, "w") as sls_file: sls_file.write(yaml.dump(preserve, Dumper=friendly_dumper, default_flow_style=False)) uid = pwd.getpwnam("salt").pw_uid gid = grp.getgrnam("salt").gr_gid for path in [stack_default, "{}/{}".format(stack_default, 'ceph'), pathname]: os.chown(path, uid, gid)
def unison_sync(paths_to_sync): """Do unison sync and retry a few times if it fails since peers may not be ready for sync. Returns list of synced units or None if one or more peers was not synced. """ log('Synchronizing CA (%s) to all peers.' % (', '.join(paths_to_sync)), level=INFO) keystone_gid = grp.getgrnam(KEYSTONE_USER).gr_gid # NOTE(dosaboy): This will sync to all peers who have already provided # their ssh keys. If any existing peers have not provided their keys yet, # they will be silently ignored. unison.sync_to_peers(peer_interface='cluster', paths=paths_to_sync, user=SSH_USER, verbose=True, gid=keystone_gid, fatal=True) synced_units = peer_units() if len(unison.collect_authed_hosts('cluster')) != len(synced_units): log("Not all peer units synced due to missing public keys", level=INFO) return None else: return synced_units
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))
def chown(self, tarinfo, targetpath): """Set owner of targetpath according to tarinfo. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid try: if tarinfo.issym() and hasattr(os, "lchown"): os.lchown(targetpath, u, g) else: if sys.platform != "os2emx": os.chown(targetpath, u, g) except EnvironmentError, e: raise ExtractError("could not change owner")