Skip to content

Instantly share code, notes, and snippets.

@linkdd
Created July 4, 2012 09:15
Show Gist options
  • Select an option

  • Save linkdd/3046292 to your computer and use it in GitHub Desktop.

Select an option

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

linkdd commented Jul 4, 2012

Copy link
Copy Markdown
Author

$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

ajeebkp23 commented Oct 2, 2019

Copy link
Copy Markdown

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

@linkdd

linkdd commented Oct 2, 2019

Copy link
Copy Markdown
Author

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