Skip to content

Instantly share code, notes, and snippets.

@FooBarQuaxx
Forked from wcang/chroot.py
Created June 19, 2017 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FooBarQuaxx/d2f1ee608a4aa9e8336663858ba898ec to your computer and use it in GitHub Desktop.
Save FooBarQuaxx/d2f1ee608a4aa9e8336663858ba898ec to your computer and use it in GitHub Desktop.
Demo code to try out chroot using python context manager
import os
import sys
import shutil
class chroot:
def __init__(self, root_dir):
self.root_dir = root_dir
def __enter__(self):
self.real_root = os.open("/",os.O_RDONLY)
folders = [ 'proc', 'sys', 'dev', 'home' ]
for folder in folders:
full_path = self.root_dir + "/" + folder
if not os.path.exists(full_path):
os.mkdir(full_path)
os.system("mount --bind /%s %s" % (folder, full_path))
os.chroot(self.root_dir)
def __exit__(self, exc_type, exc_val, traceback):
os.system("umount {/proc,/sys}")
os.system("sync")
os.fchdir(self.real_root)
os.chroot('.')
os.close(self.real_root)
os.system("umount -l %s/home" % self.root_dir)
os.system("umount -l %s/dev" % self.root_dir)
if __name__ == '__main__':
with chroot("/mnt"):
with open("/test.txt", "w") as f:
f.write("hi\n")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment