rulu ruru

post Vlastní GeoIPLookup databáze a vyhledávání v ní

February 11th, 2009

Filed under: python — starenka @ 20:40
Tags: , , , ,

Narazil jsem na zajímavej spotík s odkazem na dump geoip databáze k volnému použití. A protože linuxový geoiplookup háže při dotazu na ip v lepším případě stát a v horším vůbec nic, musel jsem si prostě zapřehánět a napsat jednoduchý vyhledávání (zdroják) nad staženou databází napsat samička…

#!/usr/bin/env python

import MySQLdb,sys,string

if(len(sys.argv) == 2):
    try:
        db = MySQLdb.connect("localhost", "root", "", "geoip")
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit (1)
    print \nGeoIPLookup for ‘+sys.argv[1]
    print (len(sys.argv[1])+16) * ‘=’
    ip = sys.argv[1].split(‘.’)
    ip = (int(ip[0])*256+int(ip[1]))*256+int(ip[2])
    cursor = db.cursor()
    cursor.execute(‘SELECT * FROM ip_group_city WHERE ip_start <= %s ORDER BY ip_start DESC LIMIT 1′,ip)
    city = cursor.fetchone()
    cursor.execute(‘SELECT name FROM fips_regions WHERE code = %s AND country_code = %s’,(city[2],city[1]))
    region = cursor.fetchone()
    cursor.execute(‘SELECT name FROM fips_countries WHERE code = %s’,city[1])
    country = cursor.fetchone()
    print "City:\t\t%s\nRegion:\t\t%s, %s\nCountry:\t%s, %s\nGPS (lat/lon):\t%s/%s\nZIP:\t\t%s" % (city[3],region[0],city[2],country[0],city[1],city[5],city[6],city[4])
    db.close()
else: print ‘Pass the ip, pal!’

2 Comments

  1. dobrej objev, akorat ta tabulka fips_countries je v tom dumpu jako iso3166_countries. coz nevim co je za haluz teda, kazdopadne kdyz to predelam na iso3166_countries ten skript tak error. Neznam pythony btw

    Traceback (most recent call last):
    File “./geolookup.py”, line 23, in
    print “City:\t\t%s\nRegion:\t\t%s, %s\nCountry:\t%s, %s\nGPS (lat/lon):\t%s/%s\nZIP:\t\t%s” % (city[3],region[0],city[2],country[0],city[1],city[5],city[6],city[4])
    TypeError: ‘NoneType’ object is unsubscriptable

    _________________________________
    188:CREATE TABLE `iso3166_countries` (

    Comment by Ben Afleck — May 18, 2010 @ 18:48

  2. No typoval bych to na fakt, ze strukturu ty db zmenili :)

    Comment by starenka — May 20, 2010 @ 13:13

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

ruldrurd
© starenka 2oo7, cute alien monster by noizcut, original theme by Laurentiu Piron - customized by starenka | proudly powered by WordPress