Python os 模块,getuid() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.getuid()。
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe and enabled
"""
if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
return False
if hasattr(os, "getuid") and hasattr(os, "geteuid"):
# check process uid == effective uid
if os.geteuid() != os.getuid():
return None
if hasattr(os, "getgid") and hasattr(os, "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def choose_boundary():
global _prefix
if _prefix is None:
hostid = socket.gethostbyname(socket.gethostname())
try:
uid = `os.getuid()`
except:
uid = '1'
try:
pid = `os.getpid()`
except:
pid = '1'
_prefix = hostid + '.' + uid + '.' + pid
timestamp = '%.3f' % time.time()
seed = `random.randint(0,32767)`
return _prefix + '.' + timestamp + '.' + seed
def choose_boundary():
"""Return a string usable as a multipart boundary.
The string chosen is unique within a single program run,and
incorporates the user id (if available),process id (if available),
and current time. So it's very unlikely the returned string appears
in message text,but there's no guarantee.
The boundary contains dots so you have to quote it in the header."""
global _prefix
import time
if _prefix is None:
import socket
try:
hostid = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
hostid = '127.0.0.1'
try:
uid = repr(os.getuid())
except AttributeError:
uid = '1'
try:
pid = repr(os.getpid())
except AttributeError:
pid = '1'
_prefix = hostid + '.' + uid + '.' + pid
return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())
# Subroutines for decoding some common content-transfer-types
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe and enabled
"""
if sys.flags.no_user_site:
return False
if hasattr(os, "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
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
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
def prep(self, container):
container.execute(["pacman", "-Syy", "--noconfirm", "sudo", "binutils",
"fakeroot"])
uid = os.getuid()
if uid == 0:
# if we're running as root,make up a user
uid = 1000
container.execute(["useradd", "-m", "-u", str(uid), "packagecore"])
container.execute(["/bin/bash", "-c",
"echo 'packagecore ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers"])
# create our working directory
self._pkgBuildDir = os.path.join(container.getSharedDir(),
"arch-pkg")
_makeDir(self._pkgBuildDir)
self.generatePKGBUILDFile(container)
##
# @brief Build the arch package.
#
# @param container The container to build in.
#
# @return None
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def t07(w):
pretty = '%s t7' % __file__
print(pretty)
base = os.path.join(w.path, '.ave', 'config')
os.makedirs(base)
try:
authkeys = ave.config.load_authkeys(w.path)
print('FAIL %s: could load invalid config: %s' % (pretty, authkeys))
return False
except Exception, e:
name = ave.pwd.getpwuid_name(os.getuid())
if 'run "ave-config --bootstrap=%s"' % name not in unicode(e):
print('FAIL %s: wrong error: %s' % (pretty, e))
return False
return True
# used by t8-t10. calls os._exit() so only use from within child process.
def load(path):
if not os.path.exists(path):
user = ave.pwd.getpwuid_name(os.getuid())
raise Exception(
'no such configuration file: %s\n\nrun "ave-config --bootstrap=%s" '
'to create one with default values' % (path, user)
)
config = None
with open(path) as f:
try:
config = json.load(f)
except Exception, e:
raise Exception(
'invalid config file %s: not valid JSON encoding: %s' % (path,e)
)
if type(config) != dict:
raise Exception(
'invalid config file %s: contents is not a dictionary: %s'
% (path, type(config))
)
return config
def t07(w):
pretty = '%s t7' % __file__
print(pretty)
base = os.path.join(w.path, e))
return False
return True
# used by t8-t10. calls os._exit() so only use from within child process.
def load(path):
if not os.path.exists(path):
user = ave.pwd.getpwuid_name(os.getuid())
raise Exception(
'no such configuration file: %s\n\nrun "ave-config --bootstrap=%s" '
'to create one with default values' % (path, type(config))
)
return config
def init_database(self):
# check if dir exists,create sqlite directory and set OS permissions to 777
sqlite_dir_path = os.path.join(self.game_dir,'sqlite')
if not os.path.exists(sqlite_dir_path):
os.makedirs(sqlite_dir_path)
os.chmod(sqlite_dir_path, 0777)
conn = sqlite3.connect(self.garden_db_path)
init_table_string = """CREATE TABLE IF NOT EXISTS garden (
plant_id tinytext PRIMARY KEY,
owner text,
description text,
age text,
score integer,
is_dead numeric
)"""
c = conn.cursor()
c.execute(init_table_string)
conn.close()
# init only,creates and sets permissions for garden db and json
if os.stat(self.garden_db_path).st_uid == os.getuid():
os.chmod(self.garden_db_path, 0666)
open(self.garden_json_path, 'a').close()
os.chmod(self.garden_json_path, 0666)
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print("Admin check failed,assuming not an admin.")
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
raise(RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))
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 check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def startedConnecting(self, connector):
fd = connector.transport.fileno()
stats = os.fstat(fd)
try:
filestats = os.stat(connector.transport.addr)
except:
connector.stopConnecting()
return
if stat.S_IMODE(filestats[0]) != 0600:
log.msg("socket mode is not 0600: %s" % oct(stat.S_IMODE(stats[0])))
elif filestats[4] != os.getuid():
log.msg("socket not owned by us: %s" % stats[4])
elif filestats[5] != os.getgid():
log.msg("socket not owned by our group: %s" % stats[5])
# XXX reenable this when i can fix it for cygwin
#elif filestats[-3:] != stats[-3:]:
# log.msg("socket doesn't have same create times")
else:
log.msg('conecting OK')
return
connector.stopConnecting()
def getuser():
"""Get the username from the environment or password database.
First try various environment variables,the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
# Bind the name getpass to the appropriate function
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
def is_there_SUID_shell():
if os.getuid() == 0:
return True
if os.path.isfile('/usr/local/roots'):
return True
if local_pw_read():
#send_msg("%sLocal PW present.\n" % greenPlus,False)
binarymake = make_SUID_root_binary(local_pw_read(), None)
#send_msg(binarymake[1],False)
if binarymake[0]: #we have successfully created a temp root shell
return True
return False
return False
def do_root(command):
if os.getuid() == 0:
output = subprocess.Popen("%s" % command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = output.stdout.read()
err = output.stderr.read()
if output.wait() != 0:
return (False, '%sWe are root,but there was an error.\n%s%s' % (blue_star, yellow_star, err))
return (True, "%s\n" % out)
else:
if not is_there_SUID_shell():
return (False, '%sThere is no root shell to perform this command. See [rooter] manual entry.\n' % red_minus)
output = subprocess.Popen("/usr/local/roots \"%s\"" % (command), stderr=subprocess.PIPE)
out = output.stdout.read()
err = output.stderr.read()
if err != '':
return (False, '%sThere is a root shell to perform this command, "%s\n" % out)
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def compat_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 = compat_getenv('HOME')
else:
import pwd
try:
pwent = pwd.getpwnam(path[1:i])
except KeyError:
return path
userhome = pwent.pw_dir
userhome = userhome.rstrip('/')
return (userhome + path[i:]) or '/'
def __init__(self):
self.cron = CronTab(user=True)
params = PARAMS % os.getuid()
filename = os.path.join(os.path.expanduser('~'), FILE)
desktop_environment = get_desktop_environment()
if desktop_environment == 'gnome' or \
desktop_environment == 'unity' or \
desktop_environment == 'budgie-desktop':
gset = GSET_GNOME % filename
elif desktop_environment == "mate":
gset = GSET_MATE % filename
elif desktop_environment == "cinnamon":
gset = GSET_CINNAMON % filename
else:
gset = None
if gset is not None:
self.command = '{0};{1};{2} {3} && {4}'.format(SLEEP, params,
EXEC, SCRIPT, gset)
else:
self.command = None
def effectivelyReadable(self):
uid = os.getuid()
euid = os.geteuid()
gid = os.getgid()
egid = os.getegid()
# This is probably true most of the time,so just let os.access()
# handle it. Avoids potential bugs in the rest of this function.
if uid == euid and gid == egid:
return os.access(self.name, os.R_OK)
st = os.stat(self.name)
# This may be wrong depending on the semantics of your OS.
# i.e. if the file is -------r--,does the owner have access or not?
if st.st_uid == euid:
return st.st_mode & stat.S_IRUSR != 0
# See comment for UID check above.
groups = os.getgroups()
if st.st_gid == egid or st.st_gid in groups:
return st.st_mode & stat.S_IRGRP != 0
return st.st_mode & stat.S_IROTH != 0
def effectivelyReadable(self):
uid = os.getuid()
euid = os.geteuid()
gid = os.getgid()
egid = os.getegid()
# This is probably true most of the time,does the owner have access or not?
if st.st_uid == euid:
return st.st_mode & stat.S_IRUSR != 0
# See comment for UID check above.
groups = os.getgroups()
if st.st_gid == egid or st.st_gid in groups:
return st.st_mode & stat.S_IRGRP != 0
return st.st_mode & stat.S_IROTH != 0
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print "Admin check failed,assuming not an admin."
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
raise RuntimeError, "Unsupported operating system for this module: %s" % (
os.name,)
def __init__(self, config: CheriConfig):
self.installAsRoot = os.getuid() == 0
self.cheriCXX = self.cheriCC.parent / "clang++"
archBuildFlags = {
"CHERI":config.cheriBitsStr,
"CHERI_CC":str(self.cheriCC),
"CHERI_CXX":str(self.cheriCXX),
"CHERI_LD":str(config.sdkBinDir / "ld.lld"),
"TARGET": "mips",
"TARGET_ARCH": "mips64"
}
if self.mipsOnly:
archBuildFlags = {"TARGET":"mips", "TARGET_ARCH":"mips64", "WITHOUT_LIB32": True}
# keep building a cheri kernel even with a mips userspace (mips may be broken...)
# self.kernelConfig = "MALTA64"
super().__init__(config, archBuildFlags=archBuildFlags)
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def getos():
dagitim=platform.dist()
dagitim=dagitim[0]
mimari=platform.machine()
osys=platform.system()
unumber = os.getuid()
zaman=time.ctime()
if unumber==0:
kulanici="root"
else:
kulanici="No root"
bilgi="""
============================
CPU: {}
OS: {}
DAGITIM: {}
KULANICI: {}
ZAMAN: {}
============================""".format(mimari,osys,dagitim,kulanici,zaman)
print(bilgi)
def chown(self, cpioinfo, cpiogetpath):
"""Set owner of cpiogetpath according to cpioinfo.
"""
if PWD and hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
try:
g = GRP.getgrgid(cpioinfo.gid)[2]
except KeyError:
g = os.getgid()
try:
u = PWD.getpwuid(cpioinfo.uid)[2]
except KeyError:
u = os.getuid()
try:
if cpioinfo.issym() and hasattr(os, "lchown"):
os.lchown(cpiogetpath, u, g)
else:
if sys.platform != "os2emx":
os.chown(cpiogetpath, g)
except EnvironmentError:
raise ExtractError("could not change owner")
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def root_check():
# Check for root.
if os.getuid() != 0:
print("User is not Root.")
sys.exit(103)
if "linux" not in sys.platform.lower():
print("Wrong OS.")
sys.exit(104)
return 0
# Handler for ctrl+c Event.
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def compat_expanduser(path):
"""Expand ~ and ~user constructions. If user or $HOME is unknown, 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 = compat_getenv('HOME')
else:
import pwd
try:
pwent = pwd.getpwnam(path[1:i])
except KeyError:
return path
userhome = pwent.pw_dir
userhome = userhome.rstrip('/')
return (userhome + path[i:]) or '/'
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var), "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def getuser():
"""Get the username from the environment or password database.
First try various environment variables,the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
# Bind the name getpass to the appropriate function