Created
January 26, 2026 05:50
-
-
Save bacher09/5d740a39710f6b14f805c71b2515fab5 to your computer and use it in GitHub Desktop.
Filter mmdb by country
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| import argparse | |
| import csv | |
| import os.path | |
| import pathlib | |
| import maxminddb | |
| import netaddr | |
| def list_ipv4(mmdb_path: str, country_code: str): | |
| ip_list = [] | |
| with maxminddb.open_database(mmdb_path) as mmdb_reader: | |
| for net, info in mmdb_reader: | |
| cc = info.get('country', {}).get('iso_code') | |
| if cc is None: | |
| continue | |
| if cc == country_code: | |
| network = netaddr.IPNetwork(str(net)) | |
| if network.version == 4: | |
| ip_list.append(network) | |
| return netaddr.cidr_merge(ip_list) | |
| def main(args: [str] | None = None): | |
| parser = argparse.ArgumentParser(description="List IPs for country code") | |
| parser.add_argument('--output-format', type=str, choices=("text", "nft"), default='text') | |
| parser.add_argument('--mmdb', type=pathlib.Path) | |
| parser.add_argument('country_code', type=str) | |
| namespace = parser.parse_args(args) | |
| optimized = list_ipv4(str(namespace.mmdb), namespace.country_code.upper()) | |
| if namespace.output_format == 'text': | |
| for cidr in optimized: | |
| print(str(cidr)) | |
| elif namespace.output_format == 'nft': | |
| print(" elements = {") | |
| for cidr in optimized: | |
| print(" {cidr!s},".format(cidr=cidr)) | |
| print(" }") | |
| if __name__ == '__main__': | |
| main() |
This file contains hidden or 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
| maxminddb==3.0.0 | |
| netaddr==1.3.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment