Get email upon changed IP address

Setup a cron script to check for changed IP address at reboot and each hour. Uses mailutils to setup an email server on your PC. b Note:

  • intended for devices with IPv6/IPv4 public internet addresses.
  1. install email daemon
    apt install mailutils
    
  2. test email daemon. Port 25 is blocked by many home ISPs.
    echo "testing" | mail -s "test" [email protected]
    

    Check /var/log/mail.log for Connection timed out errors that may indicate port 25 is blocked by your ISP. You might config for port 587 in that case.

  3. create executable ~/checkIP.sh
    #!/bin/bash
    set -u
    emailaddr=$1
    
    CurIP=$(hostname -I | tr -d [:space:]) 
    
    OldIP=$(tr ' ' '\n' < ~/.current_ip) #space to \n for consistency
    
    if [[ ${CurIP} != ${OldIP} ]]; then
      echo -e "IP change detected\n $CurIP \n $OldIP"
      echo "New IP address: ${CurIP} (old address: ${OldIP} )" | mail -s "IP address change: $(hostname)" "$emailaddr"
      echo -e "${CurIP}" > ~/.current_ip
    fi
    

    be sure it’s executable

    chmod +x ~/checkIP.sh
    
  4. Edit your cron schedule
    crontab -e
    

    add at the top:

    SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin
    

    add at the bottom:

    @reboot ~/checkIP.sh [email protected]
    @hourly ~/checkIP.sh [email protected]
    

Notes

Reference

Tags:

Categories:

Updated:

Leave a Comment