def pivot_namespace_root(target): old_root = tempfile.mkdtemp(prefix='.oldroot', dir=target) pivot_root(target, old_root) os.chdir('/') pivoted_old_root = '/' + os.path.basename(old_root) umount(pivoted_old_root) os.rmdir(pivoted_old_root)
def mount_etc_files(target_dir_func): tmpfs = tempfile.mkdtemp(prefix='.etc', dir=target_dir_func('/')) mount('tmpfs', tmpfs, 'tmpfs', MS_NOEXEC | MS_NODEV | MS_NOSUID, 'size=1m') def write_and_mount_file(path, content): tmpfile = os.path.join(tmpfs, os.path.basename(path)) with open(tmpfile, 'w') as fp: fp.write(content) target = target_dir_func(path) if not os.path.exists(target): open(target, 'w').close() bind_mount(tmpfile, target) for etc_path in ('/etc/resolv.conf', '/etc/hosts'): etc_content = open(etc_path).read() write_and_mount_file(etc_path, etc_content) write_and_mount_file('/etc/hostname', socket.gethostname() + '\n') umount(tmpfs) os.rmdir(tmpfs)