Python pygeoip.GeoIP() Examples

The following are 22 code examples of pygeoip.GeoIP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygeoip , or try the search function .
Example #1
Source File: make_geoip_table.py    From edx2bigquery with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, gipdataset=GIPDATASET, giptable=GIPTABLE, geoipdat='GeoIP2-City.mmdb', version=2):

        # geoip version 1: GeoIPCity.dat
        # geoip version 2: GeoIP2-City.mmdb

        if not os.path.exists(geoipdat):
            raise Exception("---> [make_geoip_table] Error! Missing file %s for local geoip" % geoipdat)
        self.gipdataset = gipdataset
        self.giptable = giptable
        self.gipfn = self.giptable + ".json"
        self.version = version
        if version==1:
            self.gi = pygeoip.GeoIP(geoipdat, pygeoip.MEMORY_CACHE)
        else:
            self.gi = geoip2.database.Reader(geoipdat)
        self.nchanged = 0 
Example #2
Source File: dnsproxy.py    From arkc-client with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        dns_blacklist = kwargs.pop('dns_blacklist')
        dns_servers = kwargs.pop('dns_servers')
        dns_tcpover = kwargs.pop('dns_tcpover', [])
        dns_timeout = kwargs.pop('dns_timeout', 2)
        super(self.__class__, self).__init__(*args, **kwargs)
        self.dns_servers = list(dns_servers)
        self.dns_tcpover = tuple(dns_tcpover)
        self.dns_intranet_servers = [x for x in self.dns_servers if is_local_addr(x)]
        self.dns_blacklist = set(dns_blacklist)
        self.dns_timeout = int(dns_timeout)
        self.dns_cache = ExpireCache(max_size=65536)
        self.dns_trust_servers = set(['8.8.8.8', '8.8.4.4', '2001:4860:4860::8888', '2001:4860:4860::8844'])
        for dirname in ('.', '/usr/share/GeoIP/', '/usr/local/share/GeoIP/'):
            filename = os.path.join(dirname, 'GeoIP.dat')
            if os.path.isfile(filename):
                geoip = pygeoip.GeoIP(filename)
                for dnsserver in self.dns_servers:
                    if ':' not in dnsserver and geoip.country_name_by_addr(parse_hostport(dnsserver, 53)[0]) not in ('China',):
                        self.dns_trust_servers.add(dnsserver)
                break 
Example #3
Source File: geolocation.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 6 votes vote down vote up
def init_reducer(self):
        """Initialize the geolocation object for use by a reducer."""
        super(GeolocationMixin, self).init_reducer()
        # Copy the remote version of the geolocation data file to a local file.
        # This is required by the GeoIP call, which assumes that the data file is located
        # on a local file system.
        self.temporary_data_file = tempfile.NamedTemporaryFile(prefix='geolocation_data')
        with self.geolocation_data_target().open() as geolocation_data_input:
            while True:
                transfer_buffer = geolocation_data_input.read(1024)
                if transfer_buffer:
                    self.temporary_data_file.write(transfer_buffer)
                else:
                    break
        self.temporary_data_file.seek(0)

        self.geoip = pygeoip.GeoIP(self.temporary_data_file.name, pygeoip.STANDARD) 
Example #4
Source File: DC_dbparser.py    From dc-toolkit with GNU General Public License v3.0 6 votes vote down vote up
def geo_ip(res_type, ip):
    try:
        import pygeoip
        gi = pygeoip.GeoIP('GeoIP.dat')
        if res_type == 'name':
            return gi.country_name_by_addr(ip)
        if res_type == 'cc':
            return gi.country_code_by_addr(ip)
        return gi.country_code_by_addr(ip)
    except Exception as e:
        print e
        return ''

#----------------------------------------------------------------------
# Search
#---------------------------------------------------------------------- 
Example #5
Source File: search_ip_geolitecity.py    From python-hacker with Apache License 2.0 5 votes vote down vote up
def get_geoip():
    return pygeoip.GeoIP("GeoLiteCity.dat")

#打印IP信息 
Example #6
Source File: geolocation.py    From pypkjs with MIT License 5 votes vote down vote up
def _get_position(self, success, failure):
        try:
            resp = requests.get('http://ip.42.pl/raw')
            resp.raise_for_status()
            ip = resp.text
            gi = pygeoip.GeoIP('%s/GeoLiteCity.dat' % os.path.dirname(__file__))
            record = gi.record_by_addr(ip)
            if record is None:
                if callable(failure):
                    self.runtime.enqueue(failure)
        except (requests.RequestException, pygeoip.GeoIPError):
            if callable(failure):
                self.runtime.enqueue(failure)
        else:
            self.runtime.enqueue(success, Position(self.runtime, Coordinates(self.runtime, record['longitude'], record['latitude'], 1000), round(time.time() * 1000))) 
Example #7
Source File: proxylib.py    From arkc-client with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, regions):
        self.regions = set(regions)
        try:
            import pygeoip
            self.geoip = pygeoip.GeoIP(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'GeoIP.dat'))
        except StandardError as e:
            logging.error('DirectRegionFilter init pygeoip failed: %r', e)
            sys.exit(-1) 
Example #8
Source File: 011根据ip查询地理位置.py    From PythonGUIDemo with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.gi = pygeoip.GeoIP("./GeoLiteCity.dat")
        # 创建主窗口,用于容纳其它组件
        self.root = tkinter.Tk()
        # 给主窗口设置标题内容
        self.root.title("全球定位ip位置(离线版)")
        # 创建一个输入框,并设置尺寸
        self.ip_input = tkinter.Entry(self.root,width=30)

        # 创建一个回显列表
        self.display_info = tkinter.Listbox(self.root, width=50)

        # 创建一个查询结果的按钮
        self.result_button = tkinter.Button(self.root, command = self.find_position, text = "查询")

    # 完成布局 
Example #9
Source File: pygeoip_test.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def geoip_country(): 
    path = 'GeoIP.dat'
    gi = pygeoip.GeoIP(path)
    print(gi.country_code_by_name('google.com'))
    print(gi.country_code_by_addr('64.233.161.99'))
    print(gi.country_name_by_name('google.com'))
    print(gi.country_name_by_addr('64.233.161.99')) 
Example #10
Source File: pygeoip_test.py    From Mastering-Python-for-Networking-and-Security with MIT License 5 votes vote down vote up
def geoip_city():
    path = 'GeoLiteCity.dat'
    gic = pygeoip.GeoIP(path)
    print(gic.record_by_addr('64.233.161.99'))
    print(gic.record_by_name('google.com'))
    print(gic.region_by_name('google.com'))
    print(gic.region_by_addr('64.233.161.99')) 
Example #11
Source File: geoip.py    From conary with Apache License 2.0 5 votes vote down vote up
def __init__(self, paths):
        if paths and pygeoip is None:
            raise TypeError("pygeoip module is not installed")
        self.dbs = [pygeoip.GeoIP(x, pygeoip.MMAP_CACHE) for x in paths] 
Example #12
Source File: run.py    From doxbox with MIT License 5 votes vote down vote up
def ipinfo(ip_address):
    geoip = pygeoip.GeoIP("extras/GeoLiteCity.dat")
    ip_data = geoip.record_by_addr(ip_address)
    return flask.jsonify(ip_data) 
Example #13
Source File: run.py    From doxbox with MIT License 5 votes vote down vote up
def geoip():
    description = """
    When working with metadata, IP addresses often pop up as a point-of-interest.
    Using Maxmind and Google Map's APIs, the GeoIP module aims to collect geolocation
    information on public IP addresses, in order to gather data on physical location during
    the reconaissance stage of the killchain. In order to make this module work, please provide a
    Google Maps API key."""

    form = forms.GeoIPForm()

    if flask.request.method == "POST":

        geoip = pygeoip.GeoIP("extras/GeoLiteCity.dat")
        try:
            ip_data = geoip.record_by_addr(flask.request.form['ip'])
            return flask.render_template('geoip.html',
                    title="GeoIP Module", user=user, description=description, form=form,
                    latitude=ip_data["latitude"], longitude=ip_data["longitude"], ip_data=ip_data)

        except (TypeError, ValueError, socket.error):
            flask.flash("Invalid IP Address provided!", "danger")
            return flask.redirect(flask.url_for('geoip'))
    else:
        return flask.render_template('geoip.html',
                title="GeoIP Module", small="Using locational data to conduct info-gathering",
                user=user, description=description, form=form,
                latitude="0", longitude="0") 
Example #14
Source File: relay_country.py    From OrangeAssassin with Apache License 2.0 5 votes vote down vote up
def load_database(self, which=""):
        """Load the csv file and create a list of items where to search the IP.
        """
        try:
            return pygeoip.GeoIP(self["geodb" + which])
        except IOError as exc:
            self.ctxt.log.warning("Unable to open geo database file: %r", exc)
        return None 
Example #15
Source File: utils.py    From django-htk with MIT License 5 votes vote down vote up
def get_record_by_ip(ip):
    """Returns dictionary with city data containing country_code, country_name, region, city, postal_code, latitude, longitude, dma_code, metro_code, area_code, region_code and time_zone.

    http://pygeoip.readthedocs.io/en/v0.3.2/api-reference.html#pygeoip.GeoIP.record_by_addr
    """
    gi_city = get_geoip_city()
    record = {}
    if gi_city:
        record = gi_city.record_by_addr(ip)
    return record 
Example #16
Source File: utils.py    From django-htk with MIT License 5 votes vote down vote up
def get_geoip_city():
    geoip_city_db = htk_setting('HTK_LIB_GEOIP_CITY_DB')
    if geoip_city_db:
        gi_city = pygeoip.GeoIP(geoip_city_db)
    else:
        gi_city = None
    return gi_city 
Example #17
Source File: utils.py    From django-htk with MIT License 5 votes vote down vote up
def get_geoip_country():
    geoip_country_db = htk_setting('HTK_LIB_GEOIP_COUNTRY_DB')
    if geoip_country_db:
        gi_country = pygeoip.GeoIP(geoip_country_db)
    else:
        gi_country = None
    return gi_country 
Example #18
Source File: pygeoip_test.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def geoip_country(domain,ipaddress): 
    path = 'GeoIP.dat'
    gi = pygeoip.GeoIP(path)
    print(gi.country_code_by_name(domain))
    print(gi.country_name_by_addr(ipaddress)) 
Example #19
Source File: pygeoip_test.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def geoip_city(domain,ipaddress):
    path = 'GeoLiteCity.dat'
    gic = pygeoip.GeoIP(path)
    print(gic.record_by_addr(ipaddress))
    print(gic.region_by_name(domain)) 
Example #20
Source File: CyberScan.py    From CyberScan with GNU General Public License v3.0 5 votes vote down vote up
def geo_ip(host):

    try:

       rawdata = pygeoip.GeoIP('GeoLiteCity.dat')
       data = rawdata.record_by_name(host)	
       country = data['country_name']
       city = data['city']
       longi = data['longitude']
       lat = data['latitude']
       time_zone = data['time_zone']
       area_code = data['area_code']
       country_code = data['country_code']
       region_code = data['region_code']
       dma_code = data['dma_code']
       metro_code = data['metro_code']
       country_code3 = data['country_code3']
       zip_code = data['postal_code']
       continent = data['continent']

       print '[*] IP Address: ',host
       print '[*] City: ',city
       print '[*] Region Code: ',region_code
       print '[*] Area Code: ',area_code
       print '[*] Time Zone: ',time_zone
       print '[*] Dma Code: ',dma_code
       print '[*] Metro Code: ',metro_code
       print '[*] Latitude: ',lat
       print '[*] Longitude: ',longi
       print '[*] Zip Code: ',zip_code
       print '[*] Country Name: ',country
       print '[*] Country Code: ',country_code
       print '[*] Country Code3: ',country_code3
       print '[*] Continent: ',continent

    except :
           print "[*] Please verify your ip !" 
Example #21
Source File: search_ip_geolitecity.py    From python-hacker with Apache License 2.0 5 votes vote down vote up
def main():
    #实例化GeoIP对象
    gi = get_geoip()
    search_ip_info(gi) 
Example #22
Source File: hooker_analysis.py    From hooker with GNU General Public License v3.0 4 votes vote down vote up
def macroAnalyzeConnectTo(esInterrogator):
    logger.warn("Macro Analysis of IP where APK are connecting")
    logger.warn("------------------------------------------------")

    connectIPs = dict()
    connectPorts = dict()
    connectURLs = dict()
    
    initEvents = esInterrogator.getAllEvents(HookerName="Network", ClassName="java.net.Socket", MethodName="connect")
    for event in initEvents:
        if "ParameterType" in event.Parameters[0].keys() and event.Parameters[0]['ParameterType'] == "java.net.InetSocketAddress":
            tmp = event.Parameters[0]['ParameterValue'].split('/')
            url = tmp[0]
            tmp = tmp[1].split(':')
            ip = tmp[0]
            port = tmp[1]
            #logger.info("url: {0}, ip: {1}, port: {2}".format(url, ip, port))
            # Get URLs
            if url not in connectURLs:
                connectURLs[url] = []
            if event.Parent not in connectURLs[url]:
                connectURLs[url].append(event.Parent)
            # Get IPs
            if ip not in connectIPs:
                connectIPs[ip] = []
            if event.Parent not in connectIPs[ip]:
                connectIPs[ip].append(event.Parent)
            # Get ports
            if port not in connectPorts:
                connectPorts[port] = []
            if event.Parent not in connectPorts[port]:
                connectPorts[port].append(event.Parent)
            
    logger.warn("------------------------------------------------")
    logger.warn("List of URLs and number XP associated :")
    for url, xp in connectURLs.iteritems():
        logger.info("URL: {0} -> number of xp: {1}".format(url, len(xp)))

    logger.warn("------------------------------------------------")
    logger.warn("List of ports and number XP associated :")
    for port, xp in connectPorts.iteritems():
        logger.info("Port: {0} -> number of xp: {1}".format(port, len(xp)))
        if port!='80' and port !='443':
            for _xp in xp:
                apk = esInterrogator.getAPKInXP(_xp)
                logger.warn("Port {0} APK: {1} {2} {3}".format(port, apk.Name, apk.Market, apk.Filesha1))
        
    logger.warn("------------------------------------------------")
    gic = pygeoip.GeoIP('GeoLiteCity.dat')
    connectCities = dict()
    for ip, xp in connectIPs.iteritems():
        city = gic.time_zone_by_addr(ip)
        if city not in connectCities:
            connectCities[city] = []
        if xp not in connectCities[city]:
            connectCities[city].append(xp)
    
    logger.warn("List of cities and XP associated :")
    for city, xp in connectCities.iteritems():
        logger.info("{0} -> number of xp: {1}".format(city, len(xp)))