Skip to content

Instantly share code, notes, and snippets.

@hurelhuyag
Last active September 7, 2020 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hurelhuyag/1792741534eef45ecb55cb65d2578a22 to your computer and use it in GitHub Desktop.
Save hurelhuyag/1792741534eef45ecb55cb65d2578a22 to your computer and use it in GitHub Desktop.
RouterOS address-list updater
#!/bin/bash
#echo -n Password /admin@192.168.0.1/ :
#read -s password
password="{Enter Your Password Here or Enable above 2 line}"
ip_bits(){
z=$1;
a=$(echo "l($z)/l(2)" | bc -l | awk '{print int($1)}');
return $((32-$a));
}
ip_add () {
ip=$1;
sshpass -p "$password" ssh admin@192.168.0.1 "ip firewall address-list add address=$ip list=mn" < /dev/null
}
ip_remove () {
ip=$1;
sshpass -p "$password" ssh admin@192.168.0.1 "ip firewall address-list remove [find list=mn address=$ip]" < /dev/null
}
echo $'\n--- fetching new list ---\n';
new_list=$(curl --silent https://ftp.apnic.net/stats/apnic/delegated-apnic-latest | grep '|MN|ipv4|' | awk -F'|' '{print $4 " " $5}'); # 218.100.84.0 256
#new_list=$(cat /home/hurlee/Downloads/delegated-apnic-latest.txt | grep '|MN|ipv4|' | awk -F'|' '{print $4 " " $5}'); # 218.100.84.0 256
updated_list='';
while IFS= read -r line; do
ip=$(echo "$line" | awk '{print $1}');
ip_count=$(echo "$line" | awk '{print $2}');
ip_bits $ip_count;
ip_bits="$?";
line="$ip/$ip_bits";
if [ -z "$updated_list" ]
then
updated_list="$line";
else
updated_list="$updated_list"$'\n'"$line";
fi
done <<< "$new_list";
echo $'\n--- fetching currently active list ---\n';
old_list=$(sshpass -p "$password" ssh admin@192.168.0.1 "ip firewall address-list print" | grep mn | awk '{print $3}'); # 218.100.84.0/24
echo $'\n--- finding no longer valid ip from currently active list ---\n';
while IFS= read -r line; do
if [[ ! $updated_list =~ "$line" ]]
then
echo "del $line";
ip_remove "$line";
fi
done <<< "$old_list";
echo $'\n--- finding new ip from new list ---\n';
while IFS= read -r line; do
if [[ ! $old_list =~ "$line" ]]
then
echo "add $line";
ip_add "$line";
fi
done <<< "$updated_list";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment