#!/usr/bin/env python3 import sys import os import subprocess p = os.path.join mounts = [ "proc", "sys", "dev", p("dev","pts"), "tmp", "run" ] def call(cmd,*args,**kwargs): proc = subprocess.Popen(cmd,*args,**kwargs) rtn = proc.wait() if rtn != 0: raise subprocess.CalledProcessError(rtn,cmd) return proc def callRtn(cmd,*args,**kwargs): proc = subprocess.Popen(cmd,*args,**kwargs) return proc.wait() def mountChroot(d): for mount in mounts: if callRtn(["mountpoint","-q",p(d,mount)]) == 0: continue call(["mount","--bind",os.path.sep + mount,p(d,mount)]) def umountChroot(d): for mount in reversed(mounts): if callRtn(["mountpoint","-q",p(d,mount)]) != 0: continue call(["umount","-lR",p(d,mount)]) def chroot(d,cmd): mountChroot(d) call(["chroot",d] + cmd) if sys.argv[1] == "-u": umountChroot(sys.argv[2]) sys.exit(0) chroot(sys.argv[1],sys.argv[2:])