|
36 | 36 |
|
37 | 37 |
|
38 | 38 | import argparse |
| 39 | +from functools import lru_cache |
39 | 40 | import pytrap |
40 | 41 | import geoip2.database |
41 | 42 |
|
|
58 | 59 | help="type of GeoLite database", |
59 | 60 | choices=['country', 'city', 'asn'], |
60 | 61 | default="country") |
| 62 | +parser.add_argument('-c', "--cache", |
| 63 | + type=int, |
| 64 | + help="number of cached lookups. If set to 0, caching is disabled.", |
| 65 | + default=128) |
61 | 66 |
|
62 | 67 | # parse command line arguments |
63 | 68 | args = parser.parse_args() |
|
88 | 93 | trap.setRequiredFmt(0, fmttype, fmtspec) |
89 | 94 | rec = pytrap.UnirecTemplate(fmtspec) |
90 | 95 |
|
91 | | - |
92 | 96 | # open GeoLite2 database reader |
93 | 97 | with geoip2.database.Reader(args.db) as reader: |
| 98 | + @lru_cache(maxsize=args.cache) |
| 99 | + def lookup_in_database(lookup_ip): |
| 100 | + #Function to look up the IP address in the GeoLite2 database. |
| 101 | + if args.type == 'city': |
| 102 | + return reader.city(lookup_ip) |
| 103 | + elif args.type == 'country': |
| 104 | + return reader.country(lookup_ip) |
| 105 | + elif args.type == 'asn': |
| 106 | + return reader.asn(lookup_ip) |
| 107 | + |
| 108 | + |
94 | 109 | # main loop |
95 | 110 | while True: |
96 | 111 | try: |
|
114 | 129 | ip = rec.get(data, field) |
115 | 130 | output.ip = ip |
116 | 131 | try: |
117 | | - if args.type == 'city': |
118 | | - geolocation = reader.city(str(ip)) |
119 | | - elif args.type == 'country': |
120 | | - geolocation = reader.country(str(ip)) |
121 | | - elif args.type == 'asn': |
122 | | - geolocation = reader.asn(str(ip)) |
| 132 | + geolocation = lookup_in_database(str(ip)) |
123 | 133 | except: |
124 | 134 | continue |
125 | 135 | if geolocation is None: |
|
0 commit comments