Skip to content

Instantly share code, notes, and snippets.

@kevinxucs
Last active January 5, 2023 22:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kevinxucs/1c23ff84cd62b6b2e3f3 to your computer and use it in GitHub Desktop.
Save kevinxucs/1c23ff84cd62b6b2e3f3 to your computer and use it in GitHub Desktop.
chroot wrapper script
#!/bin/bash
# Change this to the parent folder that holds all chroots
CHROOT_ROOT=/scratch/chroot
# DO NOT CHANGE!
chrootname="$1"
chrootdir="$CHROOT_ROOT/$chrootname"
chrootlock="$CHROOT_ROOT/$chrootname.lock"
pid=$$
usage() {
cat <<EOF
Usage: ${0##*/} chroot-name [args]
-h Print this help message
EOF
}
check_mount() {
cat /proc/mounts | grep $1 >/dev/null 2>&1
return $?
}
check_umount() {
if check_mount $1; then
umount $1
return $?
fi
}
die() {
echo >&2 $1
exit 1
}
mount_all() {
if [[ ! -d "$chrootdir" ]]; then
die "No such chroot: $chrootname"
fi
if ! check_mount "$chrootdir/dev"; then
mount --bind /dev "$chrootdir/dev"
fi
if ! check_mount "$chrootdir/dev/pts"; then
mount --bind /dev/pts "$chrootdir/dev/pts"
fi
if ! check_mount "$chrootdir/proc"; then
mount -t proc none "$chrootdir/proc"
fi
if ! check_mount "$chrootdir/sys"; then
mount -t sysfs none "$chrootdir/sys"
fi
}
umount_all() {
check_umount "$chrootdir/sys"
check_umount "$chrootdir/proc"
check_umount "$chrootdir/dev/pts"
check_umount "$chrootdir/dev"
}
clean_lock() {
pids=$(cat $chrootlock)
rm -f $chrootlock
for p in $pids; do
if ps -p $p >/dev/null; then
echo $p >> $chrootlock
fi
done
touch $chrootlock
}
if [[ -z $1 || $1 = @(-h|--help) ]]; then
usage
exit $(( $# ? 0 : 1 ))
fi
(( EUID == 0 )) || die "This script must be run with root privileges"
shift
# Add lock
if [[ ! -f "$chrootlock" ]]; then
mount_all
echo $pid > "$chrootlock"
else
clean_lock
echo $pid >> "$chrootlock"
fi
# Go chroot!
chroot "$chrootdir" /bin/bash -l "$@"
# Remove lock
sed -i '/'$pid'/d' "$chrootlock"
clean_lock
if [[ ! -s "$chrootlock" ]]; then
rm -f "$chrootlock"
umount_all
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment