当前位置: 首页>>代码示例>>Python>>正文


Python GeoIP.country_name_by_addr方法代码示例

本文整理汇总了Python中pygeoip.GeoIP.country_name_by_addr方法的典型用法代码示例。如果您正苦于以下问题:Python GeoIP.country_name_by_addr方法的具体用法?Python GeoIP.country_name_by_addr怎么用?Python GeoIP.country_name_by_addr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygeoip.GeoIP的用法示例。


在下文中一共展示了GeoIP.country_name_by_addr方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ip2country

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import country_name_by_addr [as 别名]
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)
开发者ID:sbesson,项目名称:registry,代码行数:29,代码来源:views.py

示例2: QueryManager

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import country_name_by_addr [as 别名]

#.........这里部分代码省略.........
                    self.processedserver+=1
                    gobject.idle_add(self.set_progressbar_fraction)
                    if None == self.filter or \
                                   self.filter.does_filter_match_server(server):
                        gobject.idle_add(self.tab.addServer, server)
                    else:
                        self.filterdcount+=1  # server is not added but filterd
                        
            except Empty:
                #no more threads in the queue break thread execution
                self.gui_lock = threading.RLock()
                with self.gui_lock:
                    self.threadcount -= 1
                    Log.log.debug('Thread:' + threading.current_thread().name + \
                         ' finishes working and exiting')
                    if self.threadcount == 0: #last thread reached
                        Log.log.info('Thread:' + threading.current_thread().name + \
                         ' notifying the coordinator thread that the queue ' \
                         + 'processing is finished')
                        self.messageque.put('finished')
                break
    
    def pulse_progressbar_thread(self):
        """
        This method runs as a background thread that pulse the progressbar
        of self.tab every 0.1 seconds
        """
        while True:
            try:
                message = self.pulsemessageque.get(True, 0.1)    
                if message == 'stop_pulse':
                    break
            except Empty:
                self.gui_lock = threading.RLock()
                with self.gui_lock:
                    gobject.idle_add(self.pulse_progressbar)
                    
                    
    def set_progressbar_fraction(self):
        """
        Sets the progressbar fraction. Uses the total servercount and the
        processed servercount values to calculate the fraction
        """
        if not self.abort:
            fraction = float(self.processedserver) / float(self.servercount)
            
            
            bartext = None
            if 1.0 == fraction:
                bartext = 'finished getting server status - displaying ' \
                         + str((self.servercount-self.filterdcount)) + \
                         ' servers (' + str(self.filterdcount) + ' filtered)'
                self.tab.statusbar.progressbar.set_fraction(0.0)
                
            else:
                bartext = 'fetching server status (' + str(self.processedserver) + \
                          ' / ' + str(self.servercount) + ') - ' + \
                          str(self.filterdcount) + ' servers filtered'
                self.tab.statusbar.progressbar.set_fraction(fraction)     
            self.tab.statusbar.progressbar.set_text(bartext)
                    
    def pulse_progressbar(self):
        """
        Pulse the progressbar, called by the thread using  gobject.idle_add
        """
        self.tab.statusbar.progressbar.set_text('fetching serverlist from master server')
        self.tab.statusbar.progressbar.pulse() 
       
    def set_progressbar_aborted(self):
        """
        Sets the text of the progressbar to the aborted message and resets fraction
        """    
        self.tab.statusbar.progressbar.set_text('task aborted')
        self.tab.statusbar.progressbar.set_fraction(0.0)
    
    def abort_current_task(self):
        """
        Stops the processing of the queue by setting a abort flag.
        """    
        self.gui_lock = threading.RLock()
        with self.gui_lock:
            self.abort = True
        
    def set_location(self, server):
        """
        Determine location of a server based on the ip adress of the server 
        and set it at the server object
        
        Extra threading lock used because there was some strange effects 
        without it.
        
        @param - the server object
        """
        self.geo_lock = threading.RLock()
        with self.geo_lock:
            #location = country(server.getHost())
            location = self.pygeoip.country_code_by_addr(server.getHost())
            locname = self.pygeoip.country_name_by_addr(server.getHost())
            server.set_location(location)
            server.set_location_name(locname)
开发者ID:anthonynguyen,项目名称:UrTSB,代码行数:104,代码来源:querymanager.py

示例3: index

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import country_name_by_addr [as 别名]
def index():
    res_data = {}
    verbose = False
    prettyprint = False

    try:
        client_ip = request.remote_route[0]
    except:
        client_ip = request.environ['REMOTE_ADDR']
        pass

    args = request.query_string.split('&')
    if 'v' in args:
        verbose = True

    if 'pp' in args:
        prettyprint = True

    res_data['ip'] = client_ip

    try:
        ua = request.environ['HTTP_USER_AGENT']
        user_agent = user_agents.parse(ua)
        res_data['user_agent'] = str(user_agent)
    except Exception as e:
        user_agent = False
        pass

    if user_agent and not verbose:
        if user_agent.browser.family == 'Other':
            response.set_header('Content-type', 'text/plain')
            return res_data['ip'] + '\r\n'

    try:
        ip = GeoIP(config.get('app', 'geoip_database'))
        res_data['country'] = ip.country_name_by_addr(client_ip)
        res_data['city'] = ip.record_by_addr(client_ip)
        res_data['asn'] = ip.asn_by_addr(client_ip)
    except Exception as e:
        pass

    try:
        name = reversename.from_address(client_ip)
        answers = resolver.query(name, 'PTR')
        res_data['hostname'] = []
        for answer in answers:
            res_data['hostname'].append(str(answer).rstrip('.'))
    except Exception as e:
        pass

    if user_agent and verbose:
        if user_agent.browser.family == 'Other':
            response.set_header('Content-type', 'application/json')
            if prettyprint:
                return json.dumps(
                    res_data,
                    sort_keys=True,
                    indent=4,
                    separators=(',', ': ')
                ) + '\r\n'
            return json.dumps(res_data)

    return template(
        'index',
        ua_info=res_data,
        page_title='Your IP-address is: ' + res_data['ip'],
        verbose=verbose
    )
开发者ID:stemid,项目名称:ipa.sh,代码行数:70,代码来源:app.py

示例4: hit

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import country_name_by_addr [as 别名]
def hit(request):
    stable_omero_downloads = 'http://downloads.openmicroscopy.org/latest-stable/omero'
    agent = None
    try:
        agt = request.META.get('HTTP_USER_AGENT', '')
        if agt is not None and agt.startswith("OMERO."):
            try:
                agent = Agent.objects.get(agent_name=agt)
            except Agent.DoesNotExist:
                return HttpResponseRedirect(UPGRADE_CHECK_URL)
            except:
                logger.error(traceback.format_exc())
                return HttpResponseRedirect(UPGRADE_CHECK_URL)
        else:
                return HttpResponseRedirect(UPGRADE_CHECK_URL)
    except:
        logger.error(traceback.format_exc())
        return HttpResponseRedirect(UPGRADE_CHECK_URL)
    logger.debug("Agent %s" % agent)
    
    agent_version = ''
    update = None
    try:
        agent_version = request.REQUEST.get('version')
        ver = Version.objects.get(pk=1)
        if agent_version is not None:
            try:
                regex = re.compile("^.*?[-]?(\\d+[.]\\d+([.]\\d+)?)[-]?.*?$")

                agent_cleaned = regex.match(agent_version).group(1)
                agent_split = agent_cleaned.split(".")

                local_cleaned = regex.match(ver.version).group(1)
                local_split = local_cleaned.split(".")

                rv = (agent_split < local_split)
            except:
                rv = True
            if rv:
                update = 'Please upgrade to %s. See %s for the latest version.' % (ver, stable_omero_downloads)
        else:
            update = 'Please upgrade to %s. See %s for the latest version.' % (ver, stable_omero_downloads)
    except:
        logger.debug(traceback.format_exc())
    logger.debug("Agent version %s" % agent_version)
    
    ip = None
    try:
        real_ip = None
        try:
            # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. The
            # client's IP will be the first one.
            # http://code.djangoproject.com/ticket/3872
            real_ip = request.META['HTTP_X_FORWARDED_FOR']
            logger.debug("HTTP_X_FORWARDED_FOR: %s" % real_ip) 
            real_ip = real_ip.split(",")[-1].strip()
        except KeyError:
            real_ip = request.META.get('REMOTE_ADDR')
            
        if real_ip is not None:
            try:
                ip = IP.objects.get(ip=real_ip)
            except IP.DoesNotExist:
                latitude = None
                longitude = None
                country = None
                geoip = GeoIP(settings.GEODAT, STANDARD)
                gir = geoip.record_by_addr(real_ip)
                if gir is not None:
                    latitude = gir["latitude"]
                    longitude = gir["longitude"]
                geoip = GeoIP(settings.GEOIP, MEMORY_CACHE)
                country = geoip.country_name_by_addr(real_ip)
                    
                logger.debug("IP: %s, latitude: '%s', longitude: '%s'" % (real_ip, latitude, longitude))
                ip = IP(ip=real_ip, latitude=latitude, longitude=longitude, country=country)
                ip.save()
    except Exception, x:
        logger.debug(traceback.format_exc())
        raise x
开发者ID:sbesson,项目名称:registry,代码行数:82,代码来源:views.py

示例5: GraphManager

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import country_name_by_addr [as 别名]
class GraphManager(object):
    """ Generates and processes the graph based on packets
    """

    def __init__(self, packets, layer=3, geo_ip=os.path.expanduser('~/GeoIP.dat')):
        self.graph = DiGraph()
        self.layer = layer
        self.geo_ip = None
        self.data = {}

        try:
            self.geo_ip = GeoIP(geo_ip)
        except:
            logging.warning("could not load GeoIP data")

        if self.layer == 2:
            edges = map(self._layer_2_edge, packets)
        elif self.layer == 3:
            edges = map(self._layer_3_edge, packets)
        elif self.layer == 4:
            edges = map(self._layer_4_edge, packets)
        else:
            raise ValueError("Other layers than 2,3 and 4 are not supported yet!")

        for src, dst, packet in filter(lambda x: not (x is None), edges):
            if src in self.graph and dst in self.graph[src]:
                self.graph[src][dst]['packets'].append(packet)
            else:
                self.graph.add_edge(src, dst, {'packets': [packet]})

        for node in self.graph.nodes():
            self._retrieve_node_info(node)

        for src, dst in self.graph.edges():
            self._retrieve_edge_info(src, dst)

    def get_in_degree(self, print_stdout=True):
        unsorted_degrees = self.graph.in_degree()
        return self._sorted_results(unsorted_degrees, print_stdout)

    def get_out_degree(self, print_stdout=True):
        unsorted_degrees = self.graph.out_degree()
        return self._sorted_results(unsorted_degrees, print_stdout)

    @staticmethod
    def _sorted_results(unsorted_degrees, print_stdout):
        sorted_degrees = OrderedDict(sorted(unsorted_degrees.items(), key=lambda t: t[1], reverse=True))
        for i in sorted_degrees:
            if print_stdout:
                print(sorted_degrees[i], i)
        return sorted_degrees

    def _retrieve_node_info(self, node):
        self.data[node] = {}
        if self.layer >= 3 and self.geo_ip:
            if self.layer == 3:
                self.data[node]['ip'] = node
            elif self.layer == 4:
                self.data[node]['ip'] = node.split(':')[0]

            node_ip = self.data[node]['ip']
            country = self.geo_ip.country_name_by_addr(node_ip)
            self.data[node]['country'] = country if country else 'private'
        #TODO layer 2 info?

    def _retrieve_edge_info(self, src, dst):
        edge = self.graph[src][dst]
        if edge:
            packets = edge['packets']
            edge['layers'] = set(list(itertools.chain(*[set(GraphManager.get_layers(p)) for p in packets])))
            edge['transmitted'] = sum(len(p) for p in packets)
            edge['connections'] = len(packets)

    @staticmethod
    def get_layers(packet):
        return list(GraphManager.expand(packet))

    @staticmethod
    def expand(x):
        yield x.name
        while x.payload:
            x = x.payload
            yield x.name

    @staticmethod
    def _layer_2_edge(packet):
        return packet[0].src, packet[0].dst, packet

    @staticmethod
    def _layer_3_edge(packet):
        if packet.haslayer(IP):
            return packet[1].src, packet[1].dst, packet

    @staticmethod
    def _layer_4_edge(packet):
        if any(map(lambda p: packet.haslayer(p), [TCP, UDP])):
            src = packet[1].src
            dst = packet[1].dst
            _ = packet[2]
            return "%s:%i" % (src, _.sport), "%s:%i" % (dst, _.dport), packet
#.........这里部分代码省略.........
开发者ID:HardlyHaki,项目名称:PcapViz,代码行数:103,代码来源:core.py


注:本文中的pygeoip.GeoIP.country_name_by_addr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。