本文整理汇总了Python中pygeoip.GeoIP类的典型用法代码示例。如果您正苦于以下问题:Python GeoIP类的具体用法?Python GeoIP怎么用?Python GeoIP使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GeoIP类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ip2country
def ip2country(request):
ip = str(request.REQUEST.get('ip'))
geoip = GeoIP(settings.GEOIP, MEMORY_CACHE)
c = geoip.country_name_by_addr(ip)
c+="; "
whois = os.popen("whois %s 2>&1" % ip)
file.close
for ln in whois:
'''
inetnum: 134.36.0.0 - 134.36.255.255
descr: University of Dundee
descr: Dundee DD1 4HN
descr: Scotland
netname: DUNDEE-UNIV
descr: University of Dundee
country: GB
'''
if ln.startswith("inetnum") or ln.startswith("netname") or ln.startswith("descr"):
c+=ln.split(":")[1].strip()+"; "
if ln.startswith("country"):
c+=ln.split(":")[1].strip()+"."
break
if len(c) > 400:
break
return HttpResponse(c)
示例2: get_weather
def get_weather(request):
"""Return weather of location from IP address.
https://pypi.python.org/pypi/django-ipware
https://pypi.python.org/pypi/pygeoip
https://pypi.python.org/pypi/python-forecastio
"""
ip = get_real_ip(request)
if ip is not None:
gi = GeoIP(settings.GEOIP_DATABASE, MEMORY_CACHE)
record = gi.record_by_addr(ip)
if record is not None:
try:
latitude = record['latitude']
longitude = record['longitude']
except KeyError:
return None
try:
forecast = forecastio.load_forecast(settings.DARKSKY_API_KEY, latitude, longitude)
currently = forecast.currently()
except Exception:
return None
return {
'icon': weather_icons.get(currently.icon, None),
'summary': currently.summary.lower(),
'temperature': int(currently.temperature),
'city': record.get('city', None),
'country': record.get('country_name', None),
}
else:
return None
else:
return None
示例3: run
def run(self):
log.debug("Updating mirror database")
geoip = GeoIP(Config.GEOIP_PATH_V4)
for status in mirror_statuses(unofficial_mirrors=Config.UNOFFICIAL_MIRRORS):
name = status['mirror']
if name == "a.pypi.python.org":
# don't include 'a' in the list of mirrors - it's no mirror after all
continue
time_diff = status['time_diff']
if not isinstance(time_diff, timedelta):
continue
log.debug(" Processing mirror '%s'", name)
record = geoip.record_by_name(name)
lat = record['latitude']
lon = record['longitude']
log.debug(" Age: %d, Lat: %0.5f, Lon: %0.5f", time_diff.total_seconds(), lat, lon)
try:
mirror = Mirror.objects.get(name=name)
except ObjectNotFound:
mirror = Mirror(name=name)
mirror.age = time_diff.total_seconds()
mirror.lat = lat
mirror.lon = lon
mirror.save()
self.redis.set(Config.KEY_LAST_UPDATE, time.time())
log.debug("Finished updating mirror database")
示例4: perform
def perform(self):
'''
Main method of the class that perform all actions.
'''
# Define list of coordinates
coords = []
# Open file for reading
with open(self.dict_file, "r") as lines:
try:
for line in lines.readlines():
fulldomain = line.rstrip() + "." + self.domain
try:
# Get the A target and preference of a name
answers = dns.resolver.query(fulldomain, 'A')
if type(answers) == dns.resolver.Answer:
# Iterate through answers and getting data.
for rdata in answers:
ip = rdata.address
# Create instance of GeoIP class
gi = GeoIP(self.dat_file)
# Call method record_by_addr
go = gi.record_by_addr(ip)
# Get latitude and longitude from DNS answer
coord = (go['latitude'], go['longitude'])
coords.append([fulldomain, coord])
except:
pass
# The query name does not exist.
except (dns.exception.DNSException):
pass
# Call method for generate KML file
self.to_kml(coords)
示例5: scanit
def scanit(self): #funtion to scan on record results
"""
scans a target, the target is taken from the TK box target
:return: nothing
"""
gic = GeoIP(GEOIP_DATABASE) #change this to the location of GeoLiteCity.dat
target = self.textbox.get()
if target != '' and target != 'IP or Hostname': #error checking (not empty string)
try:
target_ip = socket.gethostbyname(target) #attempts to get an ip from hostnam/ip passed through
gic = GeoIP(GEOIP_DATABASE) #load geoIP database
addr = gic.record_by_addr(target_ip) #if this works (getting ip) find address of ip
lat = addr['latitude']
lng = addr['longitude']
htmlPath = TARGET_HTML + target_ip + '.html'
mymap = maps(lat,lng,16) #create google map file
mymap.addradpoint(lat, lng, 100, "#0000FF")
mymap.draw(htmlPath)
# TODO: maybe add this back later...
# if lng != 0 and lat != 0:
# webbrowser.open(htmlPath)
self.nmap_scan(target_ip, [lat,lng])
except socket.gaierror: #if finding IP fails
print 'ERROR: Counld not get ip from hostname'
except TypeError: #if ip has no address (like 127.0.0.1) set lat and lng to 0,0
# TODO: make more graceful
print 'Could not get coordinates from GeoIP Database.'
示例6: IPToLocation
def IPToLocation(ipaddr):
from ooni.settings import config
country_file = config.get_data_file_path('GeoIP/GeoIP.dat')
asn_file = config.get_data_file_path('GeoIP/GeoIPASNum.dat')
location = {'city': None, 'countrycode': 'ZZ', 'asn': 'AS0'}
def error():
log.err("Could not find GeoIP data file in data directories."
"Try running ooniresources or"
" edit your ooniprobe.conf")
try:
country_dat = GeoIP(country_file)
location['countrycode'] = country_dat.country_code_by_addr(ipaddr)
if not location['countrycode']:
location['countrycode'] = 'ZZ'
except IOError:
error()
try:
asn_dat = GeoIP(asn_file)
location['asn'] = asn_dat.org_by_addr(ipaddr).split(' ')[0]
except:
error()
return location
示例7: IPToLocation
def IPToLocation(ipaddr):
from ooni.settings import config
country_file = config.get_data_file_path('GeoIP/GeoIP.dat')
asn_file = config.get_data_file_path('GeoIP/GeoIPASNum.dat')
location = {'city': None, 'countrycode': 'ZZ', 'asn': 'AS0'}
if not asn_file or not country_file:
log.err("Could not find GeoIP data file in data directories."
"Try running ooniresources or"
" edit your ooniprobe.conf")
return location
country_dat = GeoIP(country_file)
asn_dat = GeoIP(asn_file)
country_code = country_dat.country_code_by_addr(ipaddr)
if country_code is not None:
location['countrycode'] = country_code
asn = asn_dat.org_by_addr(ipaddr)
if asn is not None:
location['asn'] = asn.split(' ')[0]
return location
示例8: __init__
def __init__(self, database, database_v6):
self.url_map = Map([
Rule('/', endpoint='resolve'),
Rule('/favicon.ico', endpoint='favicon'),
Rule('/status', endpoint='status'),
])
self.geoip_v4 = GeoIP(database, MEMORY_CACHE)
if database_v6:
self.geoip_v6 = GeoIP(database_v6, MEMORY_CACHE)
示例9: IP_by_DataBase
def IP_by_DataBase(ip):
"""
Retorna as iformações de geo posicionamento atraver da base de dados local
Disponivel no site http://appliedsec.github.com/pygeoip/
Data Base http://dev.maxmind.com/geoip/geolite
"""
gi = GeoIP(PATH_GEOIP_CITY)
return gi.record_by_addr(ip) or {}
示例10: update_data
def update_data(self, request, commit=True):
self.user_agent = request.META.get('HTTP_USER_AGENT', None)
geo = GeoIP(settings.GEOIP_DATABASE)
self.country_code = geo.country_code_by_addr(
request.META.get('REMOTE_ADDR', None)
)
self.visitor_ip = request.META.get('REMOTE_ADDR', None)
if hasattr(request, 'user') and request.user.is_authenticated():
self.visitor = request.user
if commit:
self.save()
示例11: ip2city
class ip2city(object):
stats = {
'requests': 0,
'successes': 0,
'errors': 0,
}
geoip_v4 = None
geoip_v6 = None
def __init__(self, database, database_v6):
self.url_map = Map([
Rule('/', endpoint='resolve'),
Rule('/favicon.ico', endpoint='favicon'),
Rule('/status', endpoint='status'),
])
self.geoip_v4 = GeoIP(database, MEMORY_CACHE)
if database_v6:
self.geoip_v6 = GeoIP(database_v6, MEMORY_CACHE)
# Serve empty favicon.ico
def on_favicon(self, request):
return Response()
def on_status(self, request):
response = self.stats
response['status'] = 'Working for you.'
return Response(json.dumps(response))
def on_resolve(self, request):
ip = request.args.get('ip')
self.stats['requests'] += 1
record = {}
try:
if ':' in ip:
if self.geoip_v6:
record = self.geoip_v6.record_by_addr(ip)
self.stats['successes'] += 1
else:
self.stats['errors'] += 1
else:
record = self.geoip_v4.record_by_addr(ip)
self.stats['successes'] += 1
except GeoIPError, e:
print e
self.stats['errors'] += 1
return Response(json.dumps(record))
示例12: add_geo
def add_geo(nodes):
from pygeoip import GeoIP
gi = GeoIP(GEODB)
for k,v in nodes.items():
try:
nodes[k].update(gi.record_by_addr(v["external-ip"]))
except Exception as e:
sys.stderr.write(str(e))
sys.stderr.write("Cannot determine GeoData for %s\n"%k)
return nodes
示例13: add_coords_to_edges
def add_coords_to_edges(nodes):
from pygeoip import GeoIP
gi = GeoIP(GEODB)
for k,v in nodes.items():
for i,j in enumerate(v.get("to",[])):
data=gi.record_by_addr(j["addr"])
try:
j["latitude"]=data["latitude"]
j["longitude"]=data["longitude"]
except Exception as e: pass
return nodes
示例14: process_request
def process_request(self, request):
if 'django_timezone' in request.session:
tzname = request.session['django_timezone']
timezone.activate(pytz.timezone(tzname))
else:
ip = get_real_ip(request)
if ip is not None:
gi = GeoIP(settings.GEOIP_DATABASE, MEMORY_CACHE)
tzname = gi.time_zone_by_addr(ip)
if tzname is not None:
request.session['django_timezone'] = tzname
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
示例15: ip_to_country
def ip_to_country(ip_address):
db = GeoIP(
path.abspath(
path.join(
path.dirname(__file__),
'fixtures',
'geoip.dat'
)
),
MEMORY_CACHE
)
return Country.objects.get(
code = db.country_code_by_addr(ip_address)
)