mausezahn: use getopt_long instead of getopt
[netsniff-ng-new.git] / contrib / oui-update.py
blob3e4dddea5f1663e708ce356eeac8aedad7318fd9
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
4 # update-oui.py -- update netsniff-ng oui.conf from official IEEE OUI list
6 # Copyright (C) 2013 Tobias Klauser <tklauser@distanz.ch>
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License version 2 as
10 # published by the Free Software Foundation.
12 import os
13 import sys
14 import re
15 import getopt
16 try:
17 from urllib.request import urlopen
18 except ImportError as e:
19 raise Exception("Please run this script with Python 3")
21 DEFAULT_OUPUT_FILE = "oui.conf"
22 DEFAULT_OUI_URL = "http://standards.ieee.org/develop/regauth/oui/oui.txt"
24 OUI_PATTERN = re.compile("^\s*([a-fA-F0-9]{6})\s+\(base 16\)\s+(.*)$")
26 def usage():
27 print("""usage: {0} [OPTION...]
28 available options:
29 -f force overwrite of existing file
30 -o set output file (default: {1})
31 -u set URL to fetch OUI list from (default: {2})
32 -h show this help and exit""".format(os.path.basename(sys.argv[0]),
33 DEFAULT_OUPUT_FILE, DEFAULT_OUI_URL))
35 def main():
36 try:
37 opts, args = getopt.getopt(sys.argv[1:], "fo:u:h")
38 except getopt.GetoptError as err:
39 print(str(err))
40 usage()
41 sys.exit(-1)
43 overwrite = False
44 output_file = DEFAULT_OUPUT_FILE
45 oui_url = DEFAULT_OUI_URL
46 for o, a in opts:
47 if o == '-f':
48 overwrite = True
49 elif o == '-o':
50 output_file = a
51 elif o == '-u':
52 oui_url = a
53 elif o == '-h':
54 usage()
55 sys.exit(0)
56 else:
57 assert False, "unhandled option"
59 if not overwrite and os.path.exists(output_file):
60 print("Error: output file {} already exists".format(output_file))
61 sys.exit(-1)
63 print("Updating OUI information in {} from {}... ".format(output_file, oui_url))
65 fh_url = urlopen(oui_url)
66 encoding = fh_url.headers.get_content_charset()
67 if not encoding:
68 encoding = "utf-8"
70 ouis = []
71 for line in fh_url:
72 m = OUI_PATTERN.match(line.decode(encoding))
73 if m:
74 oui = "0x{}".format(m.group(1))
75 vendor = m.group(2).rstrip()
76 ouis.append((oui, vendor))
78 fh_file = open(output_file, 'w')
79 for oui, vendor in sorted(ouis):
80 fh_file.write("{}, {}\n".format(oui, vendor))
82 fh_url.close()
83 fh_file.close()
85 print("{} OUIs written to {}".format(len(ouis), output_file))
87 if __name__ == '__main__':
88 main()