Use with cron to maintain a dynamic IP in an NPM access list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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