本文整理汇总了Python中os.chroot方法的典型用法代码示例。如果您正苦于以下问题:Python os.chroot方法的具体用法?Python os.chroot怎么用?Python os.chroot使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.chroot方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _setup_root_filesystem
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def _setup_root_filesystem(self, root_dir):
"""Setup the filesystem layout in the given root directory.
Create a copy of the existing proc- and dev-mountpoints in the specified root
directory. Afterwards we chroot into it.
@param root_dir:
The path of the root directory that is used to execute the process.
"""
root_dir = root_dir.encode()
# Create an empty proc folder into the root dir. The grandchild still needs a
# view of the old /proc, therefore we do not mount a fresh /proc here.
proc_base = os.path.join(root_dir, b"proc")
os.makedirs(proc_base, exist_ok=True)
dev_base = os.path.join(root_dir, b"dev")
os.makedirs(dev_base, exist_ok=True)
# Create a copy of the host's dev- and proc-mountpoints.
# They are marked as private in order to not being changed
# by existing mounts during run execution.
container.make_bind_mount(b"/dev/", dev_base, recursive=True, private=True)
container.make_bind_mount(b"/proc/", proc_base, recursive=True, private=True)
os.chroot(root_dir)
示例2: change_root_directory
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def change_root_directory(directory):
""" Change the root directory of this process.
Sets the current working directory, then the process root
directory, to the specified `directory`. Requires appropriate
OS privileges for this process.
"""
try:
os.chdir(directory)
os.chroot(directory)
except Exception, exc:
error = DaemonOSEnvironmentError(
"Unable to change root directory (%(exc)s)"
% vars())
raise error
示例3: chroot
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def chroot(root):
"""
Chroot into a separate directory to isolate ourself for increased security.
"""
# preload for socket.gethostbyaddr()
import encodings.idna
try:
os.chroot(root)
os.chdir('/')
logger.info('chrooted successfully to {}'.format(root))
except Exception as e:
logger.error('could not chroot to {}: {}'.format(root, e))
return False
return True
示例4: lookupId
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def lookupId(self, root, theId):
theName = self.idCache.get(theId, None)
if theName is not None:
return theName
if root and root != '/':
curDir = os.open(".", os.O_RDONLY)
os.chdir("/")
os.chroot(root)
name = self.idLookupFn(theId)[0]
if root and root != '/':
os.chroot(".")
os.fchdir(curDir)
os.close(curDir)
self.nameCache[name] = theId
self.idCache[theId] = name
return name
示例5: testTagHandlerDoesNotExist
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def testTagHandlerDoesNotExist(self):
myRecipe = recipes.multiTagRecipe0
myRecipe += ' r.ComponentSpec(":tag", "%(taghandlerdir)s/")\n'
multitag = self.build(myRecipe, "MultiTag", returnTrove='multitag')
self.updatePkg('multitag:runtime')
fooFile = rephelp.RegularFile(
contents = 'foo\n',
perms = 0644, tags = [ 'foo' ] )
self.addComponent('foo:runtime', [('/bam', fooFile)])
oldFuncs = (os.getuid, os.lchown, os.chroot)
self.mock(os, "getuid", lambda : 0)
self.mock(os, "lchown", lambda x, y, z : None)
self.mock(os, "chroot", lambda x :None)
# this fixes a race between new tag handler process exiting and
# writing files into the pipe for that tag handler; we let the
# write finish before the handler process terminates
origExec = os.execve
self.mock(os, "execve", lambda *args : (time.sleep(0.1),
origExec(*args)))
rc, txt = self.captureOutput(self.updatePkg, 'foo:runtime',
_removeBokenPipeErrors=True)
self.assertEquals(txt.lstrip(), '[foo] [Errno 2] No such file or directory\nerror: /usr/libexec/conary/tags/foo failed\n')
示例6: chroot
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def chroot(self):
os.chroot(self)
示例7: chroot
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def chroot(self):
os.chroot(self)
示例8: setUp
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def setUp(self):
self.root = self.unset
self.cwd = self.unset
self.mask = self.unset
self.daemon = False
self.pid = os.getpid()
self.patch(os, 'chroot', lambda path: setattr(self, 'root', path))
self.patch(os, 'chdir', lambda path: setattr(self, 'cwd', path))
self.patch(os, 'umask', lambda mask: setattr(self, 'mask', mask))
self.runner = UnixApplicationRunner(twistd.ServerOptions())
self.runner.daemonize = self.daemonize
示例9: test_chroot
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def test_chroot(self):
"""
L{UnixApplicationRunner.setupEnvironment} changes the root of the
filesystem if passed a non-L{None} value for the C{chroot} parameter.
"""
self.runner.setupEnvironment("/foo/bar", ".", True, None, None)
self.assertEqual(self.root, "/foo/bar")
示例10: test_noChroot
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def test_noChroot(self):
"""
L{UnixApplicationRunner.setupEnvironment} does not change the root of
the filesystem if passed L{None} for the C{chroot} parameter.
"""
self.runner.setupEnvironment(None, ".", True, None, None)
self.assertIs(self.root, self.unset)
示例11: setupEnvironment
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def setupEnvironment(self, chroot, rundir, nodaemon, umask, pidfile):
"""
Set the filesystem root, the working directory, and daemonize.
@type chroot: C{str} or L{None}
@param chroot: If not None, a path to use as the filesystem root (using
L{os.chroot}).
@type rundir: C{str}
@param rundir: The path to set as the working directory.
@type nodaemon: C{bool}
@param nodaemon: A flag which, if set, indicates that daemonization
should not be done.
@type umask: C{int} or L{None}
@param umask: The value to which to change the process umask.
@type pidfile: C{str} or L{None}
@param pidfile: If not L{None}, the path to a file into which to put
the PID of this process.
"""
daemon = not nodaemon
if chroot is not None:
os.chroot(chroot)
if rundir == '.':
rundir = '/'
os.chdir(rundir)
if daemon and umask is None:
umask = 0o077
if umask is not None:
os.umask(umask)
if daemon:
from twisted.internet import reactor
self.config["statusPipe"] = self.daemonize(reactor)
if pidfile:
with open(pidfile, 'wb') as f:
f.write(intToBytes(os.getpid()))
示例12: contain
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def contain(command, image_name, image_dir, container_id, container_dir):
try:
linux.unshare(linux.CLONE_NEWNS) # create a new mount namespace
except RuntimeError as e:
if getattr(e, 'args', '') == (1, 'Operation not permitted'):
print('Error: Use of CLONE_NEWNS with unshare(2) requires the '
'CAP_SYS_ADMIN capability (i.e. you probably want to retry '
'this with sudo)')
raise e
# TODO: we added MS_REC here. wanna guess why?
linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)
new_root = create_container_root(
image_name, image_dir, container_id, container_dir)
print('Created a new root fs for our container: {}'.format(new_root))
# Create mounts (/proc, /sys, /dev) under new_root
linux.mount('proc', os.path.join(new_root, 'proc'), 'proc', 0, '')
linux.mount('sysfs', os.path.join(new_root, 'sys'), 'sysfs', 0, '')
linux.mount('tmpfs', os.path.join(new_root, 'dev'), 'tmpfs',
linux.MS_NOSUID | linux.MS_STRICTATIME, 'mode=755')
# Add some basic devices
devpts_path = os.path.join(new_root, 'dev', 'pts')
if not os.path.exists(devpts_path):
os.makedirs(devpts_path)
linux.mount('devpts', devpts_path, 'devpts', 0, '')
makedev(os.path.join(new_root, 'dev'))
os.chroot(new_root) # TODO: replace with pivot_root
os.chdir('/')
# TODO: umount2 old root (HINT: see MNT_DETACH in man 2 umount)
os.execvp(command[0], command)
示例13: contain
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def contain(command, image_name, image_dir, container_id, container_dir):
new_root = create_container_root(
image_name, image_dir, container_id, container_dir)
print('Created a new root fs for our container: {}'.format(new_root))
# TODO: time to say goodbye to the old mount namespace,
# see "man 2 unshare" to get some help
# HINT 1: there is no os.unshare(), time to use the linux module we made
# just for you!
# HINT 2: the linux module includes both functions and constants!
# e.g. linux.CLONE_NEWNS
# TODO: remember shared subtrees?
# (https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt)
# Make / a private mount to avoid littering our host mount table.
# Create mounts (/proc, /sys, /dev) under new_root
linux.mount('proc', os.path.join(new_root, 'proc'), 'proc', 0, '')
linux.mount('sysfs', os.path.join(new_root, 'sys'), 'sysfs', 0, '')
linux.mount('tmpfs', os.path.join(new_root, 'dev'), 'tmpfs',
linux.MS_NOSUID | linux.MS_STRICTATIME, 'mode=755')
# Add some basic devices
devpts_path = os.path.join(new_root, 'dev', 'pts')
if not os.path.exists(devpts_path):
os.makedirs(devpts_path)
linux.mount('devpts', devpts_path, 'devpts', 0, '')
for i, dev in enumerate(['stdin', 'stdout', 'stderr']):
os.symlink('/proc/self/fd/%d' % i, os.path.join(new_root, 'dev', dev))
# TODO: add more devices (e.g. null, zero, random, urandom) using os.mknod.
os.chroot(new_root)
os.chdir('/')
os.execvp(command[0], command)
示例14: orphansKill
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def orphansKill(rootToKill, manual_forced=False):
"""
Kill off anything that is still chrooted.
When USE_NSPAWN==False, this method manually detects the running processes
in chroot by reading the /proc file-system. When USE_NSPAWN==True, it just
relies on '/bin/machinectl terminate' call.
When manual_forced==True, the manual kill based on /proc is enforced.
"""
getLog().debug("kill orphans")
if USE_NSPAWN is False or manual_forced:
path_cache = {}
for killsig in [signal.SIGTERM, signal.SIGKILL]:
for fn in [d for d in os.listdir("/proc") if d.isdigit()]:
try:
root = os.readlink("/proc/%s/root" % fn)
if compare_two_paths_cached(root, rootToKill, path_cache):
getLog().warning("Process ID %s still running in chroot. Killing with %s...", fn, killsig)
pid = int(fn, 10)
os.kill(pid, killsig)
os.waitpid(pid, 0)
except OSError:
pass
else:
m_uuid = get_machinectl_uuid(rootToKill)
if m_uuid:
getLog().warning("Machine %s still running. Killing...", m_uuid)
os.system("/bin/machinectl terminate %s" % m_uuid)
示例15: condChroot
# 需要导入模块: import os [as 别名]
# 或者: from os import chroot [as 别名]
def condChroot(chrootPath):
if chrootPath is not None:
saved = {"ruid": os.getuid(), "euid": os.geteuid()}
setresuid(0, 0, 0)
os.chdir(chrootPath)
os.chroot(chrootPath)
setresuid(saved['ruid'], saved['euid'])