#!/bin/sh # Copyright 2011 CyberLeo, All Rights Reserved # http://wiki.cyberleo.net/wiki/CyberLeo/COPYRIGHT # Need root beyond here [ "$(id -u)" -eq 0 ] || exec sudo env J_BASE=${J_BASE} J_NAME=${J_NAME} J_USER=${J_USER} "${0}" "${@}" meh() { printf " \033[1;32m*\033[0m %s%s\n" "${jname:+${jname}: }" "${*}"; } omg() { printf " \033[1;33m*\033[0m %s%s\n" "${jname:+${jname}: }" "${*}"; } wtf() { printf " \033[1;31m*\033[0m %s%s\n" "${jname:+${jname}: }" "${*}"; exit 1; } pebkac() { [ "${*}" ] && printf "%s\n\n" "${*}" cat < [arguments] list ls list available chroots status show jail status start prepare an existing chroot for use stop undo what 'start' did enter shell spawn a shell or command within the chroot eval evaluate a shell command line within the chroot EOF exit 1 } cmd="$(basename "${0}")" jbase="${J_BASE:-$(realpath "$(dirname "${0}")/../")}" jname="${J_NAME:-$(basename "${1}")}" #" juser="${J_USER}" # Remove jail name from argument stack, if passed in [ "${J_NAME}" ] || shift # Propagate certain environment variables; sterilize the rest of the environment jenv=" LANG=${LANG} TERM=${TERM} USER=${USER} " # Create a new chroot, somehow j_init() { # Either a debian jail with debootstrap or a gentoo jail with stage3 + portage tarballs DEBOOTSTRAP_DIR="$(base)/debootstrap" "${DEBOOTSTRAP_DIR}/debootstrap" --arch=amd64 squeeze "${jdir}" } # Figure out and set jail parameters; needed for all functions that follow j_params() { jname="${1:-jname}" # Given a jail name, find and set up the jail dir jdir="${jbase}/${jname}" [ -d "${jdir}" ] || wtf "not a directory" # Where is the shell? for shell in /bin/bash /usr/bin/bash /usr/local/bin/bash /bin/sh do if [ -f "${jdir}/${shell}" ] then jshell=${shell} break fi wtf "cannot locate usable shell; is this a real jail?" done } # Jail is 'up' if /dev/pts and /proc are mounted j_up() { grep -q "^devpts ${jdir}/dev/pts devpts" /proc/mounts || return 1 grep -q "^proc ${jdir}/proc proc" /proc/mounts || return 1 return 0 } j_status() { j_up && meh "$(printf '\033[1;32mup\033[0m')" || meh "$(printf '\033[1;31mdown\033[0m')" } # Mount /dev/pts and /proc in the chroot j_start() { j_up && return 0 meh "starting ${jail} ..." mount -t devpts devpts "${jdir}/dev/pts" mount -t proc proc "${jdir}/proc" } # Execute command in chroot j_eval() { j_up || wtf "jail not up" meh "entering ${jail} ..." env -i ${jenv} /usr/bin/chroot "${jdir}" /bin/su "${juser:-${USER}}" -c "${*}" } j_shell() { j_eval "${jshell} -l" } # Unmount /dev/pts and /proc in the chroot j_stop() { j_up || return 0 meh "stopping ${jail} ..." umount "${jdir}/proc" umount "${jdir}/dev/pts" } # Populate jvars j_params "${jname}" case "${cmd}" in status) j_status ;; start) j_start ;; shell|enter) j_shell ;; eval) j_eval "${*}" ;; stop) j_stop ;; *) pebkac ;; esac