Skip to content

Instantly share code, notes, and snippets.

@3isenHeiM
Forked from PiDroid-B/actions_blacklist-update.conf
Last active February 8, 2024 10:29
Show Gist options
  • Save 3isenHeiM/35e0bb792fd33678208fcf0777521e6f to your computer and use it in GitHub Desktop.
Save 3isenHeiM/35e0bb792fd33678208fcf0777521e6f to your computer and use it in GitHub Desktop.
OPNsense track the WAN IP changes via custom cron

OPNsense Custom script and Cron to track WAN IP changes

Introduction

Sometimes my ISP changes the WAN IP address and I'd like to track it. I have Dynamic DNS so the fact that the WAN IP changes has no impact, but still.

To solve it, I need :

  • a script to update the WAN IP in a tracking file
  • a new cron command available under OPNsense GUI

Script to track the IP and update a file

  1. Create script in /usr/local/custom-scripts (or where you want) :
    vi /usr/local/custom-scripts/track-public-ip.sh
    
  2. Add the content of the according file below (don't forget to change variables)
  3. Set permissions chmod 700 /usr/local/custom-scripts/track-public-ip.sh

A cron command available under OPNsense GUI

  1. Create a .conf file in /usr/local/opnsense/service/conf/actions.d/ (your file must start with actions_) :
    vi /usr/local/opnsense/service/conf/actions.d/actions_track-wan-ip.conf
  2. Add the content of the according file below
  3. Restart and reload :

    configctl reload : action must be the filename without the prefix "actions_"

    service configd restart
    configctl track-wan-ip update-ip

A cron job

  1. Go to System > Settings > Cron and add a Job
  2. You can select your cron command in dropdown Command. It will show "Track WAN IP address and update a file in the root folder" since this is the content of the message variable in the rc file.
  3. Plan your cron as like as you want.
[update-ip]
command:/usr/local/custom-scripts/track-public-ip.sh
parameters:
type:script
description:Track WAN IP address and update a file in the root folder
message:WAN IP tracked
#!/bin/sh
TRACKING_FILE="/root/public_ip.log"
# Get Public IP adress
get_public_ip() {
# dig @resolver4.opendns.com myip.opendns.com +short -4
# OPNsense does not have dig
drill @resolver4.opendns.com myip.opendns.com | grep "myip.opendns" | grep -v ";" | awk '{print $5}'
}
update_file() {
timestamp=$(date +"%Y-%m-%d %T")
# Log the IP address and timestamp to the file
echo "$1 since $timestamp" >> $TRACKING_FILE
}
# Initialize the previous IP address
if [ -f "$TRACKING_FILE" ]; then
prev_ip=$(tail -n 1 "$TRACKING_FILE" | awk '{print $1}')
else
prev_ip=$(get_public_ip)
# Initialize the file
update_file "$prev_ip"
fi
# Get the current IP address
current_ip=$(get_public_ip)
# Check if the IP address has changed
if [ "$current_ip" != "$prev_ip" ]; then
# Write new IP to file
update_file "$current_ip"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment