Check a Port

sinnvoll in cron um regelmäßig einen Port zu testen und im Fehlerfall einmalig eine Mail zu senden
Nach Fehlerbehebung muss die Datei /var/run/checkport.pid wieder gelöscht werden.

checkport.sh
#!/bin/bash
# checkport.sh
# check a port and send once a warnmail to mailaddress
# to reset, please remove the $pid file
## need installed nmap an configured mail
while getopts s:p:m: flag
do
    case "${flag}" in
    s) s=${OPTARG};;
    p) p=${OPTARG};;
    m) m=${OPTARG};;
    esac
done
###################
function usage()
{
    echo "script to check a port"
    echo "usage: $0 -s myserver -p myportnumber -m myname@mymail.domain"
    exit 0
}
###################
if [[ -z "${s}" || -z "${p}" || -z "${m}" ]]; then
    usage
    exit 0
fi
###################
pid="/var/run/checkport.pid"
client=$(hostname)
message=$(echo -e "Port \"$p\" closed from \"$client\" to \"$s\".\rPlease remove on \"$client\" the file \"$pid\" if all ok again.")
###################
if [[ !  $p == ?(-)+([[:digit:]]) ]]; then
    echo "ERROR: Port $p is not a number -> exit"
    exit 0
fi
###################
if [[ ! "$m" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]]; then
    echo "ERROR: Mailaddress $m not good -> exit"
    exit 0
fi
###################
if [ ! -f $pid ]; then
    tmpfile=$(mktemp)
    nmap $s -p $p -oN $tmpfile >/dev/null
    if [ $(grep -c closed $tmpfile) -eq 1 ]; then
 
        echo $message | mail -s "Portalarm on $client" $m
        touch $pid
        rm $tmpfile
        echo "Port $p is closed. Send a warnmail to $m."
    else
    echo "Port $p is open."
    fi
else
    echo "$pid already exist."
fi