Skip to content

Instantly share code, notes, and snippets.

@linkdd
Created July 4, 2012 09:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save linkdd/3046292 to your computer and use it in GitHub Desktop.
Save linkdd/3046292 to your computer and use it in GitHub Desktop.
Script to manage chroot
#!/bin/bash
if [ "$UID" != "0" ]
then
echo "You have to be root" >&2
exit 1
fi
CHROOT=$1
if [ ! -f $CHROOT.in ]
then
for mnt in /dev /dev/pts /proc /sys
do
echo "-- Mounting $mnt on $CHROOT/$mnt"
mount -o bind $mnt $CHROOT/$mnt || exit 1
done
if [ -f $CHROOT.shared ]
then
cat $CHROOT.shared | while read entry
do
folder=${entry%:*}
mnt=${entry#*:}
echo "-- Mounting $folder on $CHROOT/$mnt"
mkdir -p $CHROOT/$mnt || exit 1
mount -o bind $folder $CHROOT/$mnt || exit 1
done
fi
echo "1" > $CHROOT.in
else
n=`cat $CHROOT.in`
let n=$n+1
echo "$n" > $CHROOT.in
fi
echo "-- Entering chroot"
chroot $CHROOT /usr/bin/env HOME=/root TERM=$TERM /bin/bash --login +h || exit 1;
n=`cat $CHROOT.in`
let n=$n-1
if [ "$n" = "0" ]
then
for umnt in /sys /proc /dev/pts /dev
do
echo "-- Umounting $CHROOT/$umnt"
umount $CHROOT/$umnt || exit 1
done
if [ -f $CHROOT.shared ]
then
cat $CHROOT.shared | while read entry
do
mnt=${entry#*:}
echo "-- Umounting $CHROOT/$mnt"
umount $CHROOT/$mnt || exit 1
done
fi
rm $CHROOT.in
else
echo "$n" > $CHROOT.in
fi
@linkdd
Copy link
Author

linkdd commented Jul 4, 2012

$CHROOT.shared contains shared folder to be binded in the chroot :

/home/linkdd/Documents:/mnt/shared/Documents

This will mount /home/linkdd/Documents on $CHROOT/mnt/shared/Documents, if the directory doesn't exist, it will be created.

$CHROOT.in contains the number of user currently in the chroot, when the first user enter into it, all filesystems are mounted, and when the last leaves the chroot, all filesystems are umounted

@ajeebkp23
Copy link

ajeebkp23 commented Oct 2, 2019

How to use this script (assuming I have saved above file in ~/enter-chroot.bash) ?

@linkdd
Copy link
Author

linkdd commented Oct 2, 2019

Wow, I was not expecting someone to use a script that old ( so old I didn't remember writing it :D ).

This will do the trick:

$ sudo bash /path/to/enter-chroot.bash /path/to/my/chroot

And you can create a file /path/to/my/chroot.shared to mount specific folders inside it (see my comment above).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment