linux  scripts

IP change logging

Ermittelt die aktuelle IP-Adresse von aktiven Netzwerkverbindungen und meldet wenn sich diese ändert.

#!/bin/bash

# Editieren/Erstellen und Ausführbar machen
#   sudo rm /usr/local/bin/ip-change-logging.sh
#   sudo nano /usr/local/bin/ip-change-logging.sh
#   sudo chmod +x /usr/local/bin/ip-change-logging.sh
#
# Minütlicher Job
#       crontab -e
#               *       *       *       *       *       /usr/local/bin/ip-change-logging.sh >> /tmp/ip-change-logging.log

#IP von Angeschlossenen Geräten, die nicht der Loopback-Adresse entsprechen
IP_ACTUAL=$(/usr/bin/ip addr show up | grep inet | awk '{print $2}' | egrep -v '^(127.0.0.1/8|::1/128)');
TIMESTAMP=$(date "+%d.%m.%Y %H:%M:%S");

IP_ACTUAL_FILE='/tmp/ip-change-logging.actual';
echo ${IP_ACTUAL} > ${IP_ACTUAL_FILE};
IP_ACTUAL=$(cat ${IP_ACTUAL_FILE});

IP_LAST_FILE='/tmp/ip-change-logging.last';
if [ ! -f ${IP_LAST_FILE} ]; then
    echo ${TIMESTAMP};
    echo 'NEW IP:';
    echo ${IP_ACTUAL};
    echo -e "Timestamp: ${TIMESTAMP}\nNEW IP: ${IP_ACTUAL}" | /usr/bin/mail -s "${HOSTNAME} new IP - host restart" ipchange@heister.email;
    echo ${IP_ACTUAL} > ${IP_LAST_FILE};
    exit
fi

IP_LAST=$(cat ${IP_LAST_FILE});

if [[ ${IP_ACTUAL} != ${IP_LAST} ]]; then
    echo ${TIMESTAMP};
    echo 'NEW IP:';
    echo ${IP_ACTUAL};
    echo 'OLD IP:';
    echo ${IP_LAST};
    echo -e "Timestamp: ${TIMESTAMP}\nNEW IP: ${IP_ACTUAL}\nOLD IP: ${IP_LAST}" | /usr/bin/mail -s "${HOSTNAME} new IP" ipchange@heister.email;
    echo ${IP_ACTUAL} > ${IP_LAST_FILE};
fi