本文整理匯總了Python中os.getuid方法的典型用法代碼示例。如果您正苦於以下問題:Python os.getuid方法的具體用法?Python os.getuid怎麽用?Python os.getuid使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os
的用法示例。
在下文中一共展示了os.getuid方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: isUserAdmin
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def isUserAdmin():
"""
@return: True if the current user is an 'Admin' whatever that means
(root on Unix), otherwise False.
Warning: The inner function fails unless you have Windows XP SP2 or
higher. The failure causes a traceback to be gen.loged and this
function to return False.
"""
if platform.system() == "Windows":
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
gen.log("Admin check failed, assuming not an admin.")
return False
elif platform.system() == "Linux":
return os.getuid() == 0
else:
raise RuntimeError("Unsupported operating system for this module: %s" % (os.name,))
示例2: get_privilege_level
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def get_privilege_level():
os_type = get_os_type()
if (os_type == OS_LINUX) or (os_type == OS_MACOSX) or (os_type == OS_FREEBSD):
if os.getuid() == 0:
return True
else:
return False
if os_type == OS_WINDOWS:
import ctypes
if ctypes.windll.shell32.IsUserAnAdmin():
return True
else:
return False
return False
# check if the forwarding was set properly.
示例3: drop_privileges
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def drop_privileges():
from certidude import config
import pwd
_, _, uid, gid, gecos, root, shell = pwd.getpwnam("certidude")
restricted_groups = []
restricted_groups.append(gid)
# PAM needs access to /etc/shadow
if config.AUTHENTICATION_BACKENDS == {"pam"}:
import grp
name, passwd, num, mem = grp.getgrnam("shadow")
click.echo("Adding current user to shadow group due to PAM authentication backend")
restricted_groups.append(num)
os.setgroups(restricted_groups)
os.setgid(gid)
os.setuid(uid)
click.echo("Switched %s (pid=%d) to user %s (uid=%d, gid=%d); member of groups %s" %
(getproctitle(), os.getpid(), "certidude", os.getuid(), os.getgid(), ", ".join([str(j) for j in os.getgroups()])))
os.umask(0o007)
示例4: __init__
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
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 = 'sleep 20;{0};{1} {2} {4} && {3} {4}'.format(
params, EXEC, SCRIPT, gset, NO_OUTPUT)
else:
self.command = None
示例5: get_binary_dir
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def get_binary_dir():
platform = PLATFORM.copy()
if platform["os"] == "darwin": # 64 bits anyway on Darwin
platform["arch"] = "x64"
elif platform["os"] == "windows": # 32 bits anyway on Windows
platform["arch"] = "x86"
binary_dir = os.path.join(RESOURCES_PATH, "bin", "%(os)s_%(arch)s" % platform)
# On Android, we need to copy torrent2http to ext4, since the sdcard is noexec
if platform["os"] == "android":
# Find wether on XBMC or OUYA XBMC
uid = os.getuid()
for app_id in ANDROID_XBMC_IDS:
xbmc_data_path = os.path.join("/data", "data", app_id)
if os.path.exists(xbmc_data_path) and uid == os.stat(xbmc_data_path).st_uid:
android_binary_dir = os.path.join(xbmc_data_path, "files", "plugin.video.kmediatorrent")
break
if not os.path.exists(android_binary_dir):
os.makedirs(android_binary_dir)
binary_dir = android_binary_dir
return binary_dir
示例6: test_permissions_posix
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def test_permissions_posix(self, ipc_server):
ipc_server.listen()
sockfile = ipc_server._server.fullServerName()
sockdir = pathlib.Path(sockfile).parent
file_stat = os.stat(sockfile)
dir_stat = sockdir.stat()
# pylint: disable=no-member,useless-suppression
file_owner_ok = file_stat.st_uid == os.getuid()
dir_owner_ok = dir_stat.st_uid == os.getuid()
# pylint: enable=no-member,useless-suppression
file_mode_ok = file_stat.st_mode & 0o777 == 0o700
dir_mode_ok = dir_stat.st_mode & 0o777 == 0o700
print('sockdir: {} / owner {} / mode {:o}'.format(
sockdir, dir_stat.st_uid, dir_stat.st_mode))
print('sockfile: {} / owner {} / mode {:o}'.format(
sockfile, file_stat.st_uid, file_stat.st_mode))
assert file_owner_ok or dir_owner_ok
assert file_mode_ok or dir_mode_ok
示例7: closeEvent
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def closeEvent(self, event):
if (len(self.ThreadDirc['Arp_posion']) != 0) or len(threadloading['template']) !=0:
reply = QMessageBox.question(self, 'About Exit','Are you sure to close ArpPosion?', QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
event.accept()
if getuid() == 0:
try:
for i in self.ThreadDirc['Arp_posion']:
i.stop(),i.join()
for i in threadloading['template']:
i.stop(),i.join()
threadloading['template'] = []
except:pass
self.deleteLater()
else:
pass
else:
event.ignore()
示例8: getuser
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def getuser():
"""Function to 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.
"""
# this is copied from the oroginal getpass.py
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]
示例9: valid_config_file
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def valid_config_file(config):
if not os.path.isabs(config):
log.error(
'Error: The config path is not valid. The path must be absolute.')
exit(1)
file_owner_uid = os.stat(config).st_uid
user_uid = os.getuid()
if user_uid != file_owner_uid and user_uid != 0:
log.error(
'Error: The config is not valid. User is not owner of the config or is not root.')
exit(1)
mode = stat.S_IMODE(os.stat(config).st_mode)
other_write_mode = mode & 0b10 # Check if other class write mode flag is set.
if other_write_mode:
log.error(
'Error: The config is not valid. It does not have correct ACLs. '
'Only owner should be able to write (Hint: try chmod og-rwto fix the problem).'
)
exit(1)
示例10: shell_lookup
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def shell_lookup():
"""Find an appropriate shell for the user"""
try:
usershell = pwd.getpwuid(os.getuid())[6]
except KeyError:
usershell = None
shells = [usershell, 'bash', 'zsh', 'tcsh', 'ksh', 'csh', 'sh']
for shell in shells:
if shell is None:
continue
elif os.path.isfile(shell):
return(shell)
else:
rshell = path_lookup(shell)
if rshell is not None:
dbg('shell_lookup: Found %s at %s' % (shell, rshell))
return(rshell)
dbg('shell_lookup: Unable to locate a shell')
示例11: pcocc_run
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def pcocc_run(jobid, jobname, user, indices, script, mirror_env, cmd, timeout, cluster):
#FIXME: handle pty option once we have agent support
vms = CLIRangeSet(indices, cluster)
if not user:
user = pwd.getpwuid(os.getuid()).pw_name
cmd = list(cmd)
if script:
basename = os.path.basename(cmd[0])
dest = os.path.join('/tmp', basename)
writefile(cluster, vms, cmd[0], dest, timeout)
cmd = ['bash', dest]
env = []
if mirror_env:
for e, v in os.environ.iteritems():
env.append("{}={}".format(e,v))
exit_code = multiprocess_call(cluster, vms, cmd, env, user, timeout)
sys.exit(exit_code)
示例12: get_default_dotm2ee_directory
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
def get_default_dotm2ee_directory(self):
dotm2ee = os.path.join(pwd.getpwuid(os.getuid())[5], ".m2ee")
if not os.path.isdir(dotm2ee):
try:
os.mkdir(dotm2ee)
except OSError as e:
logger.debug("Got %s: %s" % (type(e), e))
import traceback
logger.debug(traceback.format_exc())
logger.critical(
"Directory %s does not exist, and cannot be " "created!"
)
logger.critical(
"If you do not want to use .m2ee in your home "
"directory, you have to specify pidfile, "
"munin -> config_cache in your configuration "
"file"
)
sys.exit(1)
return dotm2ee
示例13: check_environ
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
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
示例14: _find_grail_rc
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
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
示例15: check_enableusersite
# 需要導入模塊: import os [as 別名]
# 或者: from os import getuid [as 別名]
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, "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