Skip to content

Instantly share code, notes, and snippets.

@RonnyAL
Last active November 20, 2023 13:21
Show Gist options
  • Save RonnyAL/c428831fc08145e8890a8f390b237ef5 to your computer and use it in GitHub Desktop.
Save RonnyAL/c428831fc08145e8890a8f390b237ef5 to your computer and use it in GitHub Desktop.
Use with cron to maintain a dynamic IP in an NPM access list.
#!/bin/bash
helpFunction()
{
echo ""
echo "Usage: $0 -i <ACL IP ID> -p <PATH TO NPM /data folder>"
echo -e "\t-i This ID can be found by querying the database"
echo -e "\t-p The path to the NPM /data folder."
echo -e "\t-d The name of the docker container running NPM."
exit 1
}
while getopts "i:p:d:" opt
do
case "$opt" in
i) acl_ip_id="$OPTARG" ;;
p) data_path="$OPTARG" ;;
d) container_name="$OPTARG" ;;
?) helpFunction ;;
esac
done
if [ -z "$acl_ip_id" ] || [ -z "$data_path" ]; then
helpFunction
fi
db_path="${data_path}/database.sqlite"
proxy_host_path="${data_path}/nginx/proxy_host"
old_ip=$(sqlite3 "${db_path}" "select address from access_list_client where id=${acl_ip_id};")
if [ -z $old_ip ]; then
echo "Couldn't fetch existing IP"
exit 1
fi
ip=$(curl -s ifconfig.me)
if [ -z $ip ]; then
echo "Couldn't fetch IP"
exit 1
fi
if ! [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Retrieved IP is invalid"
exit 1
fi
for i in 1 2 3 4; do
if [ $(echo "$ip" | cut -d. -f$i) -gt 255 ]; then
echo "Invalid IP fetched: ($ip)"
exit 1
fi
done
if [[ $old_ip == $ip ]]; then
echo "No change in IP"
exit 0
fi
sqlite3 "${db_path}" "update access_list_client SET address = '${ip}' where id = ${acl_ip_id};"
sed -i "s%${old_ip}%${ip}%g" "${proxy_host_path}/${acl_ip_id}.conf"
docker exec $container_name nginx -s reload
echo "IP updated"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment