|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import csv |
| 5 | +import requests |
| 6 | +from datetime import datetime |
| 7 | +from typing import List |
| 8 | + |
| 9 | +# keep the same import style as your example (adjust to your project layout) |
| 10 | +from ..config import Configuration |
| 11 | +from ..util.color import Color |
| 12 | +from ..util.process import Process |
| 13 | + |
| 14 | +class DBUpdater: |
| 15 | + """Updates a local database of MAC address prefixes to vendor names from IEEE registries. |
| 16 | + """ |
| 17 | + |
| 18 | + # Registry URLs (same idea as your original script) |
| 19 | + SOURCES = { |
| 20 | + "OUI": "https://standards-oui.ieee.org/oui/oui.csv", |
| 21 | + "MAM": "https://standards-oui.ieee.org/oui28/mam.csv", |
| 22 | + "OUI36": "https://standards-oui.ieee.org/oui36/oui36.csv", |
| 23 | + "IAB": "https://standards-oui.ieee.org/iab/iab.csv", |
| 24 | + } |
| 25 | + |
| 26 | + DEFAULT_FILENAME = "ieee-oui.txt" |
| 27 | + |
| 28 | + @classmethod |
| 29 | + def run(cls): |
| 30 | + |
| 31 | + Configuration.initialize(False) |
| 32 | + |
| 33 | + filename = Configuration.db_filename |
| 34 | + verbose = bool(Configuration.verbose) |
| 35 | + |
| 36 | + if os.path.exists(filename): |
| 37 | + up_to_date, last_updated = cls.is_up_to_date(filename) |
| 38 | + |
| 39 | + if up_to_date: |
| 40 | + Color.pl('{+} {G}Database is up to date ({C}%s{G}). Last update date: {C}%s{W}' % (filename, last_updated)) |
| 41 | + return |
| 42 | + if verbose: |
| 43 | + Color.pl('{!} {O}Deleting existing {R}%s{W}' % filename) |
| 44 | + os.remove(filename) |
| 45 | + |
| 46 | + try: |
| 47 | + total_written = cls.update_all(filename, verbose=verbose) |
| 48 | + except KeyboardInterrupt: |
| 49 | + Color.pl('\n{!} {O}Interrupted by user{W}') |
| 50 | + return |
| 51 | + |
| 52 | + Color.pl('\n\n{+} {G}Done{W} - Total entries written: {C}%d{W}' % total_written) |
| 53 | + |
| 54 | + @ classmethod |
| 55 | + def update_all(cls, filename: str, verbose: bool = False) -> int: |
| 56 | + """Loop selected sources, fetch, parse and append to filename. Returns count written.""" |
| 57 | + written_total = 0 |
| 58 | + with open(filename, "w", encoding="utf-8") as outfile: |
| 59 | + date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 60 | + outfile.write(f"# Registry Vendor List\n# Generated {date_str}\n") |
| 61 | + for key in cls.SOURCES.keys(): |
| 62 | + url = cls.SOURCES.get(key) |
| 63 | + Color.pl('\n{+} Processing {C}%s{W} from {O}%s{W}' % (key, url)) |
| 64 | + try: |
| 65 | + csv_content = cls.fetch_csv(url, verbose=verbose) |
| 66 | + written = cls.parse_and_write_csv(csv_content, outfile, key, verbose=verbose) |
| 67 | + written_total += written |
| 68 | + except Exception as e: |
| 69 | + print(f"Error processing {key}: {e}", file=sys.stderr) |
| 70 | + return written_total |
| 71 | + |
| 72 | + |
| 73 | + @classmethod |
| 74 | + def fetch_csv(cls, url: str, verbose: bool = False) -> str: |
| 75 | + """Download CSV content (boilerplate; uses requests).""" |
| 76 | + headers = {"User-Agent": "Mozilla/5.0 (compatible; FetchOUI/1.0; +https://github.com/kimocoder/wifite2)"} |
| 77 | + if verbose: |
| 78 | + Color.pl(' → Fetching %s' % url) |
| 79 | + response = requests.get(url, headers=headers, timeout=30) |
| 80 | + if not response.ok: |
| 81 | + raise RuntimeError(f"Failed to fetch {url}: {response.status_code} {response.reason}") |
| 82 | + if len(response.content) == 0: |
| 83 | + raise RuntimeError(f"Empty response from {url}") |
| 84 | + return response.text |
| 85 | + |
| 86 | + @classmethod |
| 87 | + def parse_and_write_csv(cls, csv_content: str, outfile, key: str, verbose: bool = False) -> int: |
| 88 | + """Parse CSV content and write MAC\tVendor lines to outfile (boilerplate).""" |
| 89 | + reader = csv.DictReader(csv_content.splitlines()) |
| 90 | + outfile.write(f"\n#\n# Start of {key} registry data\n#\n") |
| 91 | + count = 0 |
| 92 | + for row in reader: |
| 93 | + mac = row.get("Assignment") or row.get("Registry") or "" |
| 94 | + vendor = row.get("Organization Name") or row.get("Organization") or "" |
| 95 | + vendor = (vendor or "").strip() |
| 96 | + if mac and vendor: |
| 97 | + outfile.write(f"{mac}\t{vendor}\n") |
| 98 | + count += 1 |
| 99 | + outfile.write(f"#\n# End of {key} registry data. {count} entries.\n#\n") |
| 100 | + |
| 101 | + Color.p(' Wrote {C}%d{W} entries from source: {C}%s{W}' % (count, key)) |
| 102 | + return count |
| 103 | + |
| 104 | + def is_up_to_date(filename: str) -> bool: |
| 105 | + |
| 106 | + mtime = os.path.getmtime(filename) |
| 107 | + last_update = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S") |
| 108 | + age_seconds = datetime.now().timestamp() - mtime |
| 109 | + return age_seconds < (7 * 24 * 3600), last_update #if file is older than 7 days it is not up to date |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == '__main__': |
| 113 | + DBUpdater.run() |
0 commit comments