From: Antonio Ospite Date: Tue, 9 Aug 2016 11:42:49 +0000 (+0200) Subject: Initial import X-Git-Url: https://git.ao2.it/chroot_wrapper.git/commitdiff_plain/refs/heads/master?ds=sidebyside Initial import --- 09135a9721904a1b1a4d759fb5c25a2276cb7e0e diff --git a/chroot_wrapper.sh b/chroot_wrapper.sh new file mode 100755 index 0000000..da3ea81 --- /dev/null +++ b/chroot_wrapper.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# +# chroot_wrapper.sh - simplistic wrapper to make chroot more practical +# +# Copyright (C) 2016 Antonio Ospite +# +# This program is free software. It comes without any warranty, to +# the extent permitted by applicable law. You can redistribute it +# and/or modify it under the terms of the Do What The Fuck You Want +# To Public License, Version 2, as published by Sam Hocevar. See +# http://sam.zoy.org/wtfpl/COPYING for more details. + +set -e + +[ "x$1" = "x" ] && { echo "usage: $(basename $0) []" 1>&2; exit 1; } + +NEWROOT="$1" +shift + +COMMAND="$@" +[ "x$COMMAND" = "x" ] && COMMAND="/bin/bash" + +[ "$(id -u)" = "0" ] || { echo "Run this script as root." 1>&2; exit 1; } + +_mount_prereq() { + mount --bind /dev ${NEWROOT}/dev + mount --bind /dev/pts ${NEWROOT}/dev/pts + mount --bind /proc ${NEWROOT}/proc + mount --bind /sys ${NEWROOT}/sys + mount --bind /run ${NEWROOT}/run + mount --bind /tmp ${NEWROOT}/tmp +} + +_umount_prereq() +{ + umount ${NEWROOT}/tmp || : + umount ${NEWROOT}/run || : + umount ${NEWROOT}/sys || : + umount ${NEWROOT}/proc || : + umount ${NEWROOT}/dev/pts || : + umount ${NEWROOT}/dev || : +} + +_mount_prereq +trap '_umount_prereq' 0 +trap "exit 2" 1 2 3 15 + +# Unshare the UTS namespace. +# This ensures that the hostname change affects only the chrooted process. +# WIthout "unshare --uts" the host system hostname would be changed too. +# An alternative way would have been to use a tool like chname: +# http://blog.marineau.org/post/46688543379/giving-chroot-its-own-hostname-chname +unshare --uts chroot ${NEWROOT} /bin/bash -c "hostname -F /etc/hostname && exec ${COMMAND}"