TunnelKeeper/tunnelkeeper

104 lines
2.7 KiB
Bash
Executable File

#!/usr/bin/env bash
REALPATH="$(realpath $0)"
BASEDIR="${REALPATH%/*}"
mkdir -p "$BASEDIR/var"
mkdir -p "$BASEDIR/etc"
CONFFILE="$BASEDIR/etc/tunnels.conf"
if [[ ! -f "$CONFFILE" ]]; then
echo "Config file \"$CONFFILE\" does not exist"
exit 1
fi
function ruroot () {
if [[ $UID -ne 0 ]]; then
echo "You must be root to do this"
exit
fi
}
if [[ "${2}" == "--debug" ]]; then
dev=$(tty)
echo "debug enabled on $dev" > $dev
else
dev='/dev/null'
fi
case "$1" in
FORKSTART )
[[ "$3" != "/dev/null" ]] && vvv='-vvv' || vvv='' # debug mode
touch "$BASEDIR/var/${2}.connected"
while [[ -e "$BASEDIR/var/${2}.connected" ]]; do
ssh -F $vvv "${CONFFILE}" -N $2 &> $3
sleep 5
done
;;
FORKKILL )
kill $(sudo netstat -tnlp | grep "127.0.0.1:${2}" | grep -o '[0-9]*/ssh' | grep -o '[0-9]*') &> $3
;;
FORKDEL )
rm "$BASEDIR/var/${2}.connected"
;;
start)
if [[ -e "$BASEDIR/var/tunnelkeeper.pid" ]]; then
exit
fi
echo $$ > "$BASEDIR/var/tunnelkeeper.pid"
cat "$CONFFILE" | awk '/^Host / {print $2}' | xargs -I% -P0 $0 FORKSTART % $dev &
;;
stop)
rm "$BASEDIR/var/tunnelkeeper.pid"
cat "$CONFFILE" | awk '/^Host / {print $2}' | sed 's/^Host //' | xargs -I% -P0 $0 FORKDEL % $dev
cat "$CONFFILE" | grep -o 'LocalForward [0-9]* ' | grep -o '[0-9]*' | xargs -I% -P0 $0 FORKKILL % $dev
;;
install )
ruroot
mkdir -p /opt/tunnelkeeper/var
mkdir -p /opt/tunnelkeeper/etc
if [[ -f "$BASEDIR/etc/tunnels.conf" ]]; then
cp "$BASEDIR/etc/tunnels.conf" /opt/tunnelkeeper/etc
fi
cp "$REALPATH" "/opt/tunnelkeeper/tunnelkeeper"
ln -f -s /opt/tunnelkeeper/tunnelkeeper /usr/local/bin/tunnelkeeper
echo "[Unit]
Description=TunnelKeeper keeps SSH tunnels open.
After=network.target
[Service]
User=root
Group=root
Type=forking
ExecStart=/opt/tunnelkeeper/tunnelkeeper start
ExecStop=/opt/tunnelkeeper/tunnelkeeper stop
RestartSec=15
Restart=always
[Install]
WantedBy=multi-user.target" > /lib/systemd/system/tunnelkeeper.service
systemctl daemon-reload
systemctl enable tunnelkeeper.service
echo -e "\nTunnelKeeper service installed.\n"
;;
uninstall )
ruroot
rm /usr/local/bin/tunnelkeeper
rm /lib/systemd/system/tunnelkeeper.service
systemctl enable tunnelkeeper.service
systemctl daemon-reload
rm -rf /opt/tunnelkeeper
echo -e "\nTunnelKeeper service uninstalled.\n"
;;
list )
echo "---"
find "$BASEDIR/var/" -name '*.connected' | sed 's/^.*\///g; s/\.connected//g'
echo "---"
;;
config )
ruroot
vi "$CONFFILE"
;;
* )
echo -e "\nUsage: $(basename $0) start|stop|install|uninstall|config|list [--debug]\n"
;;
esac