Skip to content

Instantly share code, notes, and snippets.

@bmatthewshea
Last active March 11, 2024 09:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bmatthewshea/dc427f0c30b82429931d5896f548d550 to your computer and use it in GitHub Desktop.
Save bmatthewshea/dc427f0c30b82429931d5896f548d550 to your computer and use it in GitHub Desktop.
BASH script that uses 'whois' to lookup ASN number and display all IP4 CIDR associated to it.
#!/bin/bash
# whois-asn-ip (bash script)
# By: Brady Shea - March 15th 2020
# https://www.holylinux.net
# https://gist.github.com/bmatthewshea/dc427f0c30b82429931d5896f548d550
# The whois server to use:
WHOISHOSTNAME=whois.ripe.net
# Uncomment to remove temp files
#DEL_TEMP=true
ASN="$1"
whois_print="whois -h $WHOISHOSTNAME -- '-i origin ${ASN}'"
tempfile="/tmp/${ASN}.txt"
tempfile2="/tmp/${ASN}-core-record.txt"
regex_asn="^([as]|[AS]).*$"
usage="
$(basename "$0") [-h | --help] [ASN]
Retrieve all the IP4 addresses from a public Autonomous System Number (ASN).
Usage:
-h | --help Help
ASN Public 16-bit Autonomous System Number (ASxxxxx)
Review https://tools.ietf.org/html/rfc1930
& https://tools.ietf.org/html/rfc6793 for more.
"
### Functions
lookup_asn_desc() {
whois -h ${WHOISHOSTNAME} $ASN 2>/dev/null > ${tempfile2}
desc=`grep -m 1 -r "descr:" ${tempfile2} | cut -d ' ' -f11-`
printf "\nMain holder: %s" "$desc";
}
lookup_asn() {
whois -h ${WHOISHOSTNAME} -- "-i origin ${ASN}" 2>/dev/null > $tempfile
desc=`grep -m 1 -r "descr:" ${tempfile} | cut -d ' ' -f11-`
printf "\nAssigned to: %s" "$desc";
printf "\n\nScraping the following command for IP:\n%s\n\n" "$whois_print"
egrep 'route.*[0-9]{1,3}(?:\.[0-9]{1,3}){0,3}/[0-9]+' $tempfile
}
### Validate
if [[ "$1" == "" ]]; then
printf "\nNo argument found.\nPlease enter an ASN or --help.\nExiting.\n\n"; exit 1;
elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
printf "$usage"; exit 0;
elif ! [[ $ASN =~ $regex_asn ]]; then
printf "\nPlease check your AS number syntax.\nExiting.\n\n"; exit 1;
fi
# Execute
printf "\nWHOIS Server used: %s\n" "$WHOISHOSTNAME"
lookup_asn_desc
lookup_asn
[ -z ${DEL_TEMP} ] && exit 0 || rm ${tempfile}; rm ${tempfile2}; exit 0
@bmatthewshea
Copy link
Author

bmatthewshea commented Mar 15, 2020

Small BASH script to find all IP4 CIDR blocks on a given ASN. Good for looking up euro-trash, russian or chinese providers and mass blocking them.
Set to use RIPE database. Can be changed easily via variables.

SHEA99-2020-03-15_133153

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment