Skip to content

Instantly share code, notes, and snippets.

@mtrimarchi
Created May 30, 2020 14:00
Show Gist options
  • Save mtrimarchi/564c692e7531ae33170accc164ce1dd4 to your computer and use it in GitHub Desktop.
Save mtrimarchi/564c692e7531ae33170accc164ce1dd4 to your computer and use it in GitHub Desktop.
MikroTik add AS prefixes in routing table with a specific gateway
# request all prefixes for a specific AS
# ARGS: AS
# example: $ prefixes AS123
function prefixes() {
curl -sS https://stat.ripe.net/data/announced-prefixes/data.json\?resource\=$1 | TODAY_DATE=$(date -u +"%Y-%m-%d") jq --raw-output --arg v "$TODAY_DATE" '.data | .prefixes[] | select(.timelines[].endtime | startswith($v)) | select(.prefix|test(":")|not) | .prefix'
}
# aggregate prefixes for a specific AS
# dependency: from https://github.com/lamehost/aggregate-prefixes/
# ARGS: AS
# example: $ aggregate-prefixes-asn AS123
function aggregate-prefixes-asn() {
prefixes $1 | aggregate-prefixes
}
# create rsc file, send it to mikrotik, import rules and remove all the temp files
# ARGS: ROUTER - AS - COMMENT - GATEWAY
# example: $ mikrotik_add_routes_for_asn 192.168.88.1 AS123 "AS123 ISP Name" 123.123.123.123
function mikrotik_add_routes_for_asn() {
i=0
ASN_FILE=$2_routes.rsc
echo ""
echo "Router target: $1"
echo "AS set: $2 (comment: \"$3\")"
echo "Gateway: $4"
echo ""
for PREFIX in $(aggregate-prefixes-asn $2)
do
echo "/ip route add comment=\"$3\" dst-address=$PREFIX gateway=$4" >> $ASN_FILE
((i++))
done
echo "Configuration file created with $i rules"
echo "Sending file $ASN_FILE to router $1"
scp "$ASN_FILE" $1:"$ASN_FILE"
echo "Importing configuration file..."
ssh $1 "import $ASN_FILE"
echo "Removing remote configuration file..."
ssh $1 "file remove $ASN_FILE"
echo "Removing local configuration file..."
rm $ASN_FILE
echo "Done!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment