2 # Copyright 2011 CyberLeo, All Rights Reserved
3 # http://wiki.cyberleo.net/wiki/CyberLeo/COPYRIGHT
5 # Need root beyond here
6 [ "$(id -u)" -eq 0 ] || exec sudo "${0}" "${@}"
8 meh() { printf " \033[1;32m*\033[0m %s%s\n" "${jname:+${jname}: }" "${*}"; }
9 omg() { printf " \033[1;33m*\033[0m %s%s\n" "${jname:+${jname}: }" "${*}"; }
10 wtf() { printf " \033[1;31m*\033[0m %s%s\n" "${jname:+${jname}: }" "${*}"; exit 1; }
12 [ "${*}" ] && printf "%s\n\n" "${*}"
14 Usage: <list|ls|start|enter|exec|shell|stop> <jailname>
16 <command> <jail> [arguments]
18 ls list available jails
20 status show jail status
22 start prepare an existing jail for use
24 stop undo what 'start' did
28 shell spawn a shell or command within the jail
34 cmd="$(basename "${0}")"
35 jbase="${J_BASE:-$(realpath "$(dirname "${0}")/../")}"
36 jname="${J_NAME:-$(basename "${1}")}" #"
38 # Remove jail name from argument stack, if passed in
39 [ "${J_NAME}" ] || shift
41 # Propagate certain environment variables; sterilize the rest of the environment
48 # Create a new chroot, somehow
50 # Either a debian jail with debootstrap or a gentoo jail with stage3 + portage tarballs
51 DEBOOTSTRAP_DIR="$(base)/debootstrap" "${DEBOOTSTRAP_DIR}/debootstrap" --arch=amd64 squeeze "${jdir}"
54 # Figure out and set jail parameters; needed for all functions that follow
57 # Given a jail name, find and set up the jail dir
58 jdir="${jbase}/${jname}"
59 [ -d "${jdir}" ] || wtf "not a directory"
62 for shell in /bin/bash /usr/bin/bash /usr/local/bin/bash /bin/sh
64 if [ -f "${jdir}/${shell}" ]
69 wtf "cannot locate usable shell; is this a real jail?"
73 # Jail is 'up' if /dev/pts and /proc are mounted
75 grep -q "^devpts ${jdir}/dev/pts devpts" /proc/mounts || return 1
76 grep -q "^proc ${jdir}/proc proc" /proc/mounts || return 1
81 j_up && meh "$(printf '\033[1;32mup\033[0m')" || meh "$(printf '\033[1;31mdown\033[0m')"
84 # Mount /dev/pts and /proc in the jail
87 meh "starting ${jail} ..."
88 mount -t devpts devpts "${jdir}/dev/pts"
89 mount -t proc proc "${jdir}/proc"
94 j_up || wtf "jail not up"
95 meh "entering ${jail} ..."
96 exec env -i ${jenv} /usr/bin/chroot "${jdir}" /bin/su "${juser:-${USER}}" -c "${jshell}" -l
99 # Unmount /dev/pts and /proc in the jail
102 meh "stopping ${jail} ..."
103 umount "${jdir}/proc"
104 umount "${jdir}/dev/pts"
112 enter|exec|shell) j_exec "${@}" ;;