-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgeoipupdater.py
55 lines (49 loc) · 1.65 KB
/
geoipupdater.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Update GeoIP.dat if newer version exists on maxmind.com
Intended to run as a cronjob
"""
__author__ = 'Morten Abildgaard <[email protected]>'
__version__ = '1.1'
import logging as log
import os, sys
from cStringIO import StringIO
from datetime import datetime
from gzip import GzipFile
from requests import get, head
class GeoIP:
def __init__(self):
self.url = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz'
log.basicConfig(level=log.DEBUG,format='%(asctime)s %(levelname)s %(message)s',
filename='%s.log'%os.path.abspath(__file__)[:-3])
self.datfile = '/usr/share/GeoIP/GeoIP.dat'
log.info('Checking for newer version of %s' % self.datfile)
self.update()
exit()
def update(self):
r = head(self.url)
if r.headers and 'last-modified' in r.headers:
remote_lm = datetime.strptime(r.headers['last-modified'], '%a, %d %b %Y %H:%M:%S GMT')
local_lm = self.get_last_modified()
if remote_lm > local_lm:
log.info('Updating. remote_lm (%s) seems newer than local_lm (%s)' % (remote_lm,local_lm))
try:
r = get(self.url)
log.debug(r.headers)
data = GzipFile('','r',0,StringIO(r.content)).read()
with open(self.datfile, 'w') as f: f.write(data)
except IOError:
log.error('Unable to write to file %s' % self.datfile)
exit(sys.exc_info())
except Exception:
log.error(sys.exc_info()[1])
else:
log.info('No newer version found online')
def get_last_modified(self):
try:
return datetime.fromtimestamp(os.path.getmtime(self.datfile))
except Exception:
return datetime.fromtimestamp(1)
if __name__ == '__main__':
sys.exit(GeoIP())