#!/bin/sh # # trigger-rcmp: Trigger remote commands # Copyright (c)2014 Alexander Barton (alex@barton.de) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # Please read the file COPYING, README and AUTHORS for more information. # NAME="`basename "$0"`" RCMD_D="/usr/local/etc/rcmd.d" PATH="$PATH:/usr/local/sbin:/usr/sbin" do_rcmd() { SYSTEM="localhost" IFACE="eth0" CMD="uptime" TIMEOUT="180" . "$cnf" if [ $? -ne 0 ]; then echo "$NAME: failed to read \"$cnf\"!" return 2 fi NAME="$NAME($1)" echo "$NAME: checking system \"$SYSTEM\" ..." fping -c1 -q "$SYSTEM" 2>/dev/null if [ $? -ne 0 ]; then echo "$NAME: \"$SYSTEM\" seems to be down, wake it up ..." etherwake -b -i "$IFACE" `echo "$SYSTEM" | cut -d'.' -f1` if [ $? -ne 0 ]; then echo "$NAME: failed to wake \"$SYSTEM\"!" >&2 return 3 fi echo "$NAME: waiting for \"$SYSTEM\" to respond ..." for i in `seq 1 $TIMEOUT`; do fping -c1 -q "$SYSTEM" 2>/dev/null [ $? -ne 0 ] || break sleep 1s done fping -c1 -q "$SYSTEM" 2>/dev/null if [ $? -ne 0 ]; then echo "$NAME: failed to wake \"$SYSTEM\"!" >&2 return 4 fi sleep 3 rsys_was_running=0 else echo "$NAME: \"$SYSTEM\" is already alive, ok." rsys_was_running=1 fi echo "$NAME: calling \"$CMD\" on \"$SYSTEM\" ..." echo ssh -q "$SYSTEM" "$CMD" &2 return 5 fi else echo "$NAME: not shutting down \"$SYSTEM\", \c" [ $rsys_users -eq 1 ] \ && echo "there is 1 user logged in!" \ || echo "there are $rsys_users users logged in!" fi else echo "$NAME: \"$SYSTEM\" was already alive, not shutting down." fi [ $r -eq 0 ] && return 0 || return 1 } if [ $# -lt 1 ]; then echo "Usage: $0 [ [...]]" >&2 exit 2 fi result=0 while [ $# -gt 0 ]; do cnf="$RCMD_D/$1" if [ ! -r "$cnf" ]; then echo "$NAME: can't read \"$cnf\"!" r=1 else echo "$NAME: working on \"$1\" - `date "+%Y-%m-%d %H:%M:%S"`" do_rcmd "$1" ; r=$? echo "$NAME: done ($r) - `date "+%Y-%m-%d %H:%M:%S"`" fi [ $r -ne 0 ] && result=1 shift [ $# -gt 0 ] && echo done exit $result