Python pwd.getpwnam() Examples
The following are 30
code examples of pwd.getpwnam().
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: file_operations.py From kano-toolset with GNU General Public License v2.0 | 7 votes |
def chown_path(path, user=None, group=None): user_unsudoed = get_user_unsudoed() if not user: user = user_unsudoed if not group: group = user_unsudoed try: uid = pwd.getpwnam(user).pw_uid gid = grp.getgrnam(group).gr_gid os.chown(path, uid, gid) except KeyError as e: from kano.logging import logger logger.error( 'user {} or group {} do not match with existing'.format(user, group)) ret_val = False except OSError as e: from kano.logging import logger logger.error( 'Error while trying to chown, root priviledges needed {}'.format(e)) ret_val = False else: ret_val = True return ret_val
Example #2
Source File: deploy.py From picoCTF with MIT License | 6 votes |
def create_instance_user(problem_name, instance_number): """ Generates a random username based on the problem name. The username returned is guaranteed to not exist. Args: problem_name: The name of the problem instance_number: The unique number for this instance Returns: The created username """ converted_name = sanitize_name(problem_name) username = get_username(converted_name, instance_number) try: # Check if the user already exists. user = getpwnam(username) new = False except KeyError: create_user(username) new = True return username, new
Example #3
Source File: tarfile.py From jbox with MIT License | 6 votes |
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")
Example #4
Source File: tarfile.py From Python24 with MIT License | 6 votes |
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")
Example #5
Source File: tarfile.py From ironpython2 with Apache License 2.0 | 6 votes |
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")
Example #6
Source File: tarfile.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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")
Example #7
Source File: tarfile.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def chown(self, tarinfo, targetpath, numeric_owner): """Set owner of targetpath according to tarinfo. If numeric_owner is True, use .gid/.uid instead of .gname/.uname. """ if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: # We have to be root to do so. if numeric_owner: g = tarinfo.gid u = tarinfo.uid else: 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: os.chown(targetpath, u, g) except OSError as e: raise ExtractError("could not change owner")
Example #8
Source File: tarfile.py From recruit with Apache License 2.0 | 6 votes |
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")
Example #9
Source File: tarfile.py From vnpy_crypto with MIT License | 6 votes |
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")
Example #10
Source File: ledtool.py From P4wnP1 with GNU General Public License v3.0 | 6 votes |
def prepare(): # create control file if necessary if not os.path.exists(filepath): f = file(filepath, "w") f.write("255") # continous lit f.close() # fix ownership os.chown(filepath, pwd.getpwnam(uid).pw_uid, grp.getgrnam(gid).gr_gid) os.chmod(filepath, 0o666) # setup manual led control with open(ledpath + "trigger", "w") as trigger: trigger.write("none") # disable LED with open(ledpath + "brightness", "w") as brightness: brightness.write("1")
Example #11
Source File: tarfile.py From FuYiSpider with Apache License 2.0 | 6 votes |
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")
Example #12
Source File: test_authenticators.py From custodia with GNU General Public License v3.0 | 6 votes |
def setUpClass(cls): # Tests are depending on two existing and distinct users and groups. # We chose 'root' with uid/gid 0 and 'nobody', because both exist on # all relevant platforms. Tests use a mocked request so they run # under any user. cls.user = user = pwd.getpwnam('nobody') cls.group = group = grp.getgrgid(user.pw_gid) cls.parser = configparser.ConfigParser( interpolation=configparser.ExtendedInterpolation(), defaults={ 'other_uid': str(user.pw_uid), 'other_username': user.pw_name, 'other_gid': str(group.gr_gid), 'other_groupname': group.gr_name, } ) cls.parser.read_string(CONFIG)
Example #13
Source File: tarfile.py From FuYiSpider with Apache License 2.0 | 6 votes |
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")
Example #14
Source File: tarfile.py From jawfish with MIT License | 6 votes |
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")
Example #15
Source File: tarfile.py From BinderFilter with MIT License | 6 votes |
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")
Example #16
Source File: shutil.py From FuYiSpider with Apache License 2.0 | 5 votes |
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
Example #17
Source File: ctprobe_container_crawler.py From agentless-system-crawler with Apache License 2.0 | 5 votes |
def _get_user(self, **kwargs): """ Get the deprivileged user we are supposed to use """ ctprobe_user = kwargs.get('ctprobe_user', 'nobody') try: passwd = pwd.getpwnam(ctprobe_user) return ctprobe_user, passwd except Exception as ex: logger.error('Could not find user %s on this system: %s' % (ctprobe_user, ex)) return ctprobe_user, None
Example #18
Source File: qdisc_tool.py From synapse-tools with Apache License 2.0 | 5 votes |
def drop_perms() -> None: user = getpwnam(os.environ.get('SUDO_USER', 'nobody')) uid = user.pw_uid gid = user.pw_gid os.setgroups([]) os.setgid(gid) os.setuid(uid)
Example #19
Source File: utils.py From OpenMTC with Eclipse Public License 1.0 | 5 votes |
def create_openmtc_user(db_dir=None, log_dir=None): try: from pwd import getpwnam except ImportError: print("Could not import the 'pwd' module. Skipping user management") else: # assuming DB_DIR was created by setup already try: pw = getpwnam('openmtc') except KeyError as e: try: # add system user openmtc:openmtc # useradd --system -UM openmtc useradd = "useradd --system -UM openmtc" retcode = subprocess.call(useradd, shell=True) if retcode: raise Exception("Failed to add user 'openmtc'") pw = getpwnam('openmtc') except Exception as e: sys.stderr.write("Error creating user: %s\n" % (e, )) sys.exit(1) uid = pw.pw_uid gid = pw.pw_gid # set path permissions if db_dir: os.chown(db_dir, uid, gid) if log_dir: os.chown(log_dir, uid, gid)
Example #20
Source File: shutil.py From vnpy_crypto with MIT License | 5 votes |
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
Example #21
Source File: dock.py From drydock with GNU General Public License v2.0 | 5 votes |
def check_owner(self,paths,owner): """Check file user and group owner.""" bad_files = [] # Get uid and gid for given user usruid = getpwnam(owner)[2] grpuid = getgrnam(owner)[2] for fpath in paths: try: st = os.stat(fpath) except OSError: logging.warning("No file or directory found: %s"% fpath) continue #Get uid and gid for given file fileuid = st.st_uid filegid = st.st_uid fileusr = getpwuid(fileuid)[0] filegrp = getgrgid(fileuid)[0] if not (fileuid == usruid and grpuid == filegid): bad_files.append(fpath) if len(bad_files): self.templog['status'] = "Fail" self.templog['descr'] = "The following files should be owned by %s:%s"\ %(owner,owner) self.templog['output'] = bad_files else: self.templog['status'] = "Pass" self.templog['descr'] = "File user and group owner are correct" #self.add_check_results('check_owner') return self.templog
Example #22
Source File: posixpath.py From ironpython2 with Apache License 2.0 | 5 votes |
def 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 try: userhome = pwd.getpwuid(os.getuid()).pw_dir except KeyError: # bpo-10496: if the current user identifier doesn't exist in the # password database, return the path unchanged return path else: userhome = os.environ['HOME'] else: import pwd try: pwent = pwd.getpwnam(path[1:i]) except KeyError: # bpo-10496: if the user name from the path doesn't exist in the # password database, return the path unchanged return path userhome = pwent.pw_dir userhome = userhome.rstrip('/') return (userhome + path[i:]) or '/' # Expand paths containing shell variable substitutions. # This expands the forms $variable and ${variable} only. # Non-existent variables are left unchanged.
Example #23
Source File: CGIHTTPServer.py From ironpython2 with Apache License 2.0 | 5 votes |
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 #24
Source File: archive_util.py From ironpython2 with Apache License 2.0 | 5 votes |
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
Example #25
Source File: shutil.py From ironpython2 with Apache License 2.0 | 5 votes |
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
Example #26
Source File: application.py From exaddos with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __drop_privileges (user): """returns true if we are left with insecure privileges""" try: user = pwd.getpwnam(user) nuid = int(user.pw_uid) ngid = int(user.pw_gid) except KeyError: return False uid = os.getuid() gid = os.getgid() # not sure you can change your gid if you do not have a pid of zero try: # we must change the GID first otherwise it may fail after change UID if not gid: os.setgid(ngid) if not uid: os.setuid(nuid) cuid = os.getuid() ceid = os.geteuid() cgid = os.getgid() if cuid < 0: cuid = (1<<32) + cuid if cgid < 0: cgid = (1<<32) + cgid if ceid < 0: ceid = (1<<32) + ceid if nuid != cuid or nuid != ceid or ngid != cgid: return False except OSError: return False return True
Example #27
Source File: configuration.py From exaddos with BSD 3-Clause "New" or "Revised" License | 5 votes |
def user (_): # XXX: incomplete try: pwd.getpwnam(_) # uid = answer[2] except KeyError: raise TypeError('user %s is not found on this system' % _) return _
Example #28
Source File: posixpath.py From meddle with MIT License | 5 votes |
def 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 = os.environ['HOME'] else: import pwd try: pwent = pwd.getpwnam(path[1:i]) except KeyError: return path userhome = pwent.pw_dir userhome = userhome.rstrip('/') or userhome return userhome + path[i:] # Expand paths containing shell variable substitutions. # This expands the forms $variable and ${variable} only. # Non-existent variables are left unchanged.
Example #29
Source File: CGIHTTPServer.py From meddle with MIT License | 5 votes |
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 #30
Source File: tarfile.py From meddle with MIT License | 5 votes |
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: try: g = grp.getgrgid(tarinfo.gid)[2] except KeyError: g = os.getgid() try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: try: u = pwd.getpwuid(tarinfo.uid)[2] except KeyError: u = os.getuid() 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")