Skip to content

Instantly share code, notes, and snippets.

@ChimekKoo
Created January 15, 2024 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChimekKoo/d82316f12b5358a43cb5f8c72213e0ad to your computer and use it in GitHub Desktop.
Save ChimekKoo/d82316f12b5358a43cb5f8c72213e0ad to your computer and use it in GitHub Desktop.
iptoasn

Downloads info about IP address blocks (v4 and v6) assignees from iptoasn.com database. Creates and takes over _tmp directory, creates/overwrites data.json file with JSON array of objects in format:

{
    "ip_range": ["<first-ip>", "<last-ip>"],
    "ip_version": <4|6>,
    "assigned": <true|false>, // is this block assigned to someone
    "as": { // autonomous system that the ip block is assigned to (or null in every field if this block is not assigned)
        "number": "<asn>", // the AS number (ASN)
        "name": "<name>", // the AS name
        "country": "<country-code>" // country that the AS belongs to, in ISO 3166-1 alpha-2 format
    }
}
#!/bin/bash
mkdir _tmp
wget --quiet https://iptoasn.com/data/ip2asn-combined.tsv.gz -O _tmp/data.tsv.gz
gzip --decompress _tmp/data.tsv.gz
python3 << END
import json, ipaddress
def ip_version(ip):
return 4 if type(ipaddress.ip_address(ip)) is ipaddress.IPv4Address else 6
with open("_tmp/data.tsv", "r") as f:
data = [line.strip().split("\t") for line in f.read().split("\n") if line.strip() != ""]
data = [
{
"ip_range": [entry[0], entry[1]],
"ip_version": ip_version(entry[0]),
"assigned": entry[2] != "0",
"as": {
"number": entry[2] if entry[2] != "0" else None,
"name": entry[4] if entry[4] != "Not routed" else None,
"country": entry[3].lower() if entry[3].lower() != "none" else None
}
}
for entry in data
]
with open("data.json", "w") as f:
json.dump(data, f)
END
rm -rf _tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment