本文整理汇总了Python中os.seteuid方法的典型用法代码示例。如果您正苦于以下问题:Python os.seteuid方法的具体用法?Python os.seteuid怎么用?Python os.seteuid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.seteuid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_as
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def run_as(pwent, umask=0o22):
"""Drop privileges to given user's password entry, and set up
environment. Assumes the parent process has root privileges.
"""
os.umask(umask)
home = pwent.home
try:
os.chdir(home)
except OSError:
os.chdir("/")
# drop privs to user
os.setgroups(pwent.groups)
os.setgid(pwent.gid)
os.setegid(pwent.gid)
os.setuid(pwent.uid)
os.seteuid(pwent.uid)
os.environ["HOME"] = home
os.environ["USER"] = pwent.name
os.environ["LOGNAME"] = pwent.name
os.environ["SHELL"] = pwent.shell
os.environ["PATH"] = "/bin:/usr/bin:/usr/local/bin"
return None
示例2: drop_privileges
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def drop_privileges(uid, gid):
try:
if gid is not None:
os.setgid(gid)
os.setegid(gid)
logger.debug('switched uid to {}'.format(uid))
if uid is not None:
os.setuid(uid)
os.seteuid(uid)
logger.debug('switched gid to {}'.format(gid))
logger.info('running as {} ({}:{})'.format(args.user, uid, gid))
except Exception as e:
logger.error('dropping privileges failed: {}'.format(e))
return False
return True
示例3: callIntoPAM
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def callIntoPAM(service, user, conv):
"""A testing hook.
"""
pam = PAM.pam()
pam.start(service)
pam.set_item(PAM.PAM_USER, user)
pam.set_item(PAM.PAM_CONV, conv)
gid = os.getegid()
uid = os.geteuid()
os.setegid(0)
os.seteuid(0)
try:
pam.authenticate() # these will raise
pam.acct_mgmt()
return 1
finally:
os.setegid(gid)
os.seteuid(uid)
示例4: setUp
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def setUp(self):
self.checker = SSHPublicKeyDatabase()
self.key1 = base64.encodestring("foobar")
self.key2 = base64.encodestring("eggspam")
self.content = "t1 %s foo\nt2 %s egg\n" % (self.key1, self.key2)
self.mockos = MockOS()
self.mockos.path = FilePath(self.mktemp())
self.mockos.path.makedirs()
self.sshDir = self.mockos.path.child('.ssh')
self.sshDir.makedirs()
userdb = UserDatabase()
userdb.addUser('user', 'password', 1, 2, 'first last',
self.mockos.path.path, '/bin/shell')
self.patch(pwd, "getpwnam", userdb.getpwnam)
self.patch(os, "seteuid", self.mockos.seteuid)
self.patch(os, "setegid", self.mockos.setegid)
示例5: test_checkKeyAsRoot
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def test_checkKeyAsRoot(self):
"""
If the key file is readable, L{SSHPublicKeyDatabase.checkKey} should
switch its uid/gid to the ones of the authenticated user.
"""
keyFile = self.sshDir.child("authorized_keys")
keyFile.setContent(self.content)
# Fake permission error by changing the mode
keyFile.chmod(0000)
self.addCleanup(keyFile.chmod, 0777)
# And restore the right mode when seteuid is called
savedSeteuid = os.seteuid
def seteuid(euid):
keyFile.chmod(0777)
return savedSeteuid(euid)
self.patch(os, "seteuid", seteuid)
user = UsernamePassword("user", "password")
user.blob = "foobar"
self.assertTrue(self.checker.checkKey(user))
self.assertEquals(self.mockos.seteuidCalls, [0, 1, 0, os.getuid()])
self.assertEquals(self.mockos.setegidCalls, [2, os.getgid()])
示例6: setUp
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def setUp(self):
self.factory = OpenSSHFactory()
self.keysDir = FilePath(self.mktemp())
self.keysDir.makedirs()
self.factory.dataRoot = self.keysDir.path
self.keysDir.child("ssh_host_foo").setContent("foo")
self.keysDir.child("bar_key").setContent("foo")
self.keysDir.child("ssh_host_one_key").setContent(
keydata.privateRSA_openssh)
self.keysDir.child("ssh_host_two_key").setContent(
keydata.privateDSA_openssh)
self.keysDir.child("ssh_host_three_key").setContent(
"not a key content")
self.keysDir.child("ssh_host_one_key.pub").setContent(
keydata.publicRSA_openssh)
self.mockos = MockOS()
self.patch(os, "seteuid", self.mockos.seteuid)
self.patch(os, "setegid", self.mockos.setegid)
示例7: test_getPrivateKeysAsRoot
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def test_getPrivateKeysAsRoot(self):
"""
L{OpenSSHFactory.getPrivateKeys} should switch to root if the keys
aren't readable by the current user.
"""
keyFile = self.keysDir.child("ssh_host_two_key")
# Fake permission error by changing the mode
keyFile.chmod(0000)
self.addCleanup(keyFile.chmod, 0777)
# And restore the right mode when seteuid is called
savedSeteuid = os.seteuid
def seteuid(euid):
keyFile.chmod(0777)
return savedSeteuid(euid)
self.patch(os, "seteuid", seteuid)
keys = self.factory.getPrivateKeys()
self.assertEquals(len(keys), 2)
keyTypes = keys.keys()
self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
self.assertEquals(self.mockos.seteuidCalls, [0, os.geteuid()])
self.assertEquals(self.mockos.setegidCalls, [0, os.getegid()])
示例8: su
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def su() -> None:
"""
switch user. Useful when starting localslackirc
as a service as root user.
"""
if sys.platform.startswith('win'):
return
# Nothing to do, already not root
if os.getuid() != 0:
return
username = environ.get('PROCESS_OWNER', 'nobody')
userdata = pwd.getpwnam(username)
os.setgid(userdata.pw_gid)
os.setegid(userdata.pw_gid)
os.setuid(userdata.pw_uid)
os.seteuid(userdata.pw_uid)
示例9: get_cdv_change_code
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def get_cdv_change_code():
# cdv won't run on the dev machines as root. nfs does not allow
# root access to mounted drives. --Dave
if os.getuid() == 0 and getuid_for_path(".") != 0:
seteugid_to_login()
# fragile. XXXX
l = os.popen("cdv history -c 1").readlines()[0].split(" ")
if os.getuid() == 0:
os.seteuid(0)
#os.setegid(oldgid)
l = [x.strip() for x in l if x.strip() != ''] # remove empty strings.
x,code,x,x,x,x,dow,mo,dom,t,y = l
month = "%.2d" % (months.index(mo)+1)
dom = "%.2d" % int(dom) # single digit day of month like 3 becomes 03
t = "_".join(t.split(':')) # convert ':' to underscores in time.
return y+"_"+month+"_"+dom+"_"+t+"_"+code
示例10: validatePublicKey
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def validatePublicKey(self, pubKeyString):
home = os.path.expanduser('~%s/.ssh/' % self.name)
if home[0] == '~': # couldn't expand
return defer.fail(Unauthorized('not valid user'))
uid, gid = os.geteuid(), os.getegid()
ouid, ogid = pwd.getpwnam(self.name)[2:4]
os.setegid(ogid)
os.seteuid(ouid)
for file in ['authorized_keys', 'authorized_keys2']:
if os.path.exists(home+file):
lines = open(home+file).readlines()
for l in lines:
try:
l2 = l.split()
if len(l2) < 2:
continue
if base64.decodestring(l2[1])==pubKeyString:
os.setegid(gid)
os.seteuid(uid)
return defer.succeed('')
except binascii.Error:
pass # we caught an ssh1 key
os.setegid(gid)
os.seteuid(uid)
return defer.fail(error.ConchError('not valid key'))
示例11: main
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def main():
if os.getuid() != 0:
print("%s must be run as root. Exiting." % __package__)
sys.exit(1)
# We are running with root priveledges, which is kinda scary, so lets switch to the original user until we actually need root (if there is one)
user_uid = os.getenv("SUDO_UID")
if user_uid:
os.seteuid(int(user_uid))
# Add our custom logging formatter function to handle all logging output
formatter = utils.LoggingFormatter()
loggingHandler = logging.StreamHandler(sys.stdout)
loggingHandler.setFormatter(formatter)
logging.root.addHandler(loggingHandler)
logging.root.setLevel(logging.INFO)
signal.signal(signal.SIGINT, sig_clean_exit)
nordnm.NordNM()
示例12: __enter__
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def __enter__(self):
self.uid = os.geteuid()
if self.uid != 0:
os.seteuid(0)
log.log(logger.TRACE, "Effective user id from {} to 0".format(self.uid))
示例13: __exit__
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
log.warning("Exception {} with message {} thrown".format(exc_type, exc_val))
if self.uid != 0:
os.seteuid(self.uid)
log.log(logger.TRACE, "Effective user id from 0 to {}".format(self.uid))
self.uid = 0
示例14: _read_pref
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def _read_pref(name, domain, user, host, runas):
'''
helper function for reading the preference, either at the user level
or system level
'''
if runas:
try:
# convert to uid for later use.
uid = pwd.getpwnam(runas).pw_uid
except KeyError:
raise CommandExecutionError(
'Set to runas user {}, this user'
' does not exist.'.format(runas)
)
# need to run as the user
log.debug('Setting EUID to {}'.format(runas))
os.seteuid(uid)
if user:
user_domain, host_domain = _get_user_and_host(user, host)
log.debug('Reading key: "{}" in domain: "{}"'.format(name, domain))
value = Foundation.CFPreferencesCopyValue(name,
domain,
user_domain,
host_domain)
os.seteuid(0)
return value
#need to bring ourselves back up to root
path = '/var/root/Library/Preferences/'
d_path = os.path.join(path, domain)
log.debug('Reading key: "{}" in domain: "{}" at "{}"'.format(name, domain, d_path))
return Foundation.CFPreferencesCopyAppValue(name, domain)
示例15: _set_pref
# 需要导入模块: import os [as 别名]
# 或者: from os import seteuid [as 别名]
def _set_pref(name, value, domain, user, host, runas):
'''
sets the pref for the user not at the app value level
returns true or false if the preference was set correctly or not.
'''
if runas:
try:
# convert to uid for later use.
uid = pwd.getpwnam(runas).pw_uid
except KeyError:
raise CommandExecutionError(
'Set to runas user {}, this user'
' does not exist.'.format(runas)
)
# need to run as the user
log.debug('Setting EUID to {}'.format(runas))
os.seteuid(uid)
if user:
pref_user, pref_host = _get_user_and_host(user, host)
path = '/Library/Preferences/'
d_path = os.path.join(path, domain)
log.debug('Settting key: "{}" to value: "{}" in '
'domain: "{}" in "{}"'.format(name, value, domain, d_path))
try:
set_val = Foundation.CFPreferencesSetValue(name,
value,
domain,
pref_user,
pref_host)
Foundation.CFPreferencesAppSynchronize(domain)
os.seteuid(0)
return set_val
except BaseException:
log.warning('prefs._set_pref caught exception on user set.')
return False
path = '/var/root/Library/Preferences/'
d_path = os.path.join(path, domain)
log.debug('Settting key: "{}" to value: "{}" in'
' domain: "{}" in "{}"'.format(name, value, domain, d_path))
Foundation.CFPreferencesSetAppValue(name, value, domain)
return Foundation.CFPreferencesAppSynchronize(domain)