簡體   English   中英

如何在 Python 中使用 IP 地址查找位置?

[英]How to find location with IP address in Python?

我正在開發一個項目,需要將用戶位置存儲在我的數據庫中。 我得到了那個用戶的公共 IP 地址。 但我無法獲取用戶位置。 我嘗試了幾種方法(來自StackOverflow ),但沒有找到任何提示。 像下面這樣

url = urllib.urlopen("http://api.hostip.info/get_html.php?ip=%s&position=true" % ip)
data = re.compile('^[^\(]+\(|\)$').sub('', url.read())
print data

但我得到的結果是

Unknown Country?) (XX)
City: (Unknown City?)

其它的辦法:

import urllib

response = urllib.urlopen("http://api.hostip.info/get_html.php?ip={}&position=true".format(ip)).read()

print(response)

但結果是

Country: (Unknown Country?) (XX)
City: (Unknown City?)

Latitude: 
Longitude: 
IP: 115.xxx.xxx.xx

任何幫助,將不勝感激!

獲取 IP 地址和詳細位置的最簡單方法之一是使用http://ipinfo.io

import re
import json
from urllib2 import urlopen

url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)

IP=data['ip']
org=data['org']
city = data['city']
country=data['country']
region=data['region']

print 'Your IP detail\n '
print 'IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP)

嘗試使用pygeoip

~$ ping stackoverflow.com
PING stackoverflow.com (198.252.206.16) 56(84) bytes of data.

>>> import pygeoip
>>> GEOIP = pygeoip.GeoIP("/absolute_path/GeoIP.dat", pygeoip.MEMORY_CACHE)
>>> GEOIP.country_name_by_addr(ip)
'United States'

GeoIP.data 可在此處獲得

對於 python-3.x

def ipInfo(addr=''):
    from urllib.request import urlopen
    from json import load
    if addr == '':
        url = 'https://ipinfo.io/json'
    else:
        url = 'https://ipinfo.io/' + addr + '/json'
    res = urlopen(url)
    #response from url(if res==None then check connection)
    data = load(res)
    #will load the json response into data
    for attr in data.keys():
        #will print the data line by line
        print(attr,' '*13+'\t->\t',data[attr])

感謝所有解決方案和解決方法! 但是,我無法使用上述所有方法。

這是對我有用的:

import requests

response = requests.get("https://geolocation-db.com/json/39.110.142.79&position=true").json()

這種方法看起來簡單易用。 (我需要使用字典響應...)

將來,“geolocation-db.com”可能會變得不可用,因此可能需要其他來源!

假設您已經獲得了ip地址,您可以嘗試使用IP2Location Python庫來獲取用戶位置。 一個示例代碼是這樣的:

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data", "IPV4-COUNTRY.BIN"))

rec = database.get_all(ip)

print(rec.country_short)
print(rec.country_long)
print(rec.region)
print(rec.city)
print(rec.isp)  
print(rec.latitude)
print(rec.longitude)            
print(rec.domain)
print(rec.zipcode)
print(rec.timezone)
print(rec.netspeed)
print(rec.idd_code)
print(rec.area_code)
print(rec.weather_code)
print(rec.weather_name)
print(rec.mcc)
print(rec.mnc)
print(rec.mobile_brand)
print(rec.elevation)
print(rec.usage_type)

取決於您的要求,例如如果您想獲取用戶的國家名稱和地區名稱,您可以這樣做:

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data", "IPV4-COUNTRY.BIN"))

rec = database.get_all(ip)

user_country = rec.country_long
user_region = rec.region

更多詳細信息,您可以訪問這里: IP2Location Python 庫

Github 鏈接: IP2Location Python 庫 Github

您可以使用https://geolocation-db.com的服務支持 IPv4 和 IPv6。 返回 JSON 對象或 JSONP 回調函數。

蟒蛇2:

import urllib
import json

url = "https://geolocation-db.com/json"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data

蟒蛇3:

import urllib.request
import json

with urllib.request.urlopen("https://geolocation-db.com/json") as url:
    data = json.loads(url.read().decode())
    print(data)

一個 python 3 jsonp 示例:

import urllib.request
import json

with urllib.request.urlopen("https://geolocation-db.com/jsonp/8.8.8.8") as url:
    data = url.read().decode()
    data = data.split("(")[1].strip(")")
    print(data)

我在自己的服務器上做同樣的事情。 http://ipinfodb.com/register.php獲取 API 密鑰並嘗試:

import requests

ipdb = "http://api.ipinfodb.com/v3/ip-city/?key=<your api key>&ip="
ip_address = function_to_get_ip_address()
location = " ".join(str(requests.get(ipdb+ip_address).text).split(";")[4:7])

location的值將是COUNTRY REGION CITY

請記住,IP 地址不是精確的地理定位器。 尤其是從移動設備訪問您的網站時,您會看到 IP 地址的位置可能距離用戶的物理位置 100 英里。

這最終取決於您如何獲取計算機 IP 地址。 如果您使用的是 VPN 或其他專用網絡,則僅獲取本地 IP 地址將不會返回任何內容,就像您現在看到的那樣。 在這種情況下,您必須像這樣獲取公共 IP 地址:

url = 'http://api.hostip.info/get_json.php'
info = json.loads(urllib.urlopen(url).read())
ip = info['ip']

這是我獲取您正在尋找的所有信息的完整代碼(我使用了 freegeoip.net):

import urllib
import json

url = 'http://api.hostip.info/get_json.php'
info = json.loads(urllib.urlopen(url).read())
ip = info['ip']

urlFoLaction = "http://www.freegeoip.net/json/{0}".format(ip)
locationInfo = json.loads(urllib.urlopen(urlFoLaction).read())
print 'Country: ' + locationInfo['country_name']
print 'City: ' + locationInfo['city']
print ''
print 'Latitude: ' + str(locationInfo['latitude'])
print 'Longitude: ' + str(locationInfo['longitude'])
print 'IP: ' + str(locationInfo['ip'])

要求:

sudo add-apt-repository ppa:maxmind/ppa
sudo apt update
sudo apt install libmaxminddb0 libmaxminddb-dev mmdb-bin
sudo pip install geoip2

地理數據庫:

wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
tar xvfz GeoLite2-City.tar.gz

nginx 訪問日志示例:

python -c 'import geoip2.database
reader = geoip2.database.Reader("./GeoLite2-City/GeoLite2-City.mmdb")
for line in open("/var/log/nginx/access.log').readlines():
    response = reader.city(line.split(" ")[0])
    print(dir(response))
'

有關的:

我發現 ipinfo 提供最好的服務,並為每月最多 50k 次調用提供免費 API 使用 - 請參閱此處的“速率限制”:

import ipinfo

access_token = '123456789abc'
handler = ipinfo.getHandler(access_token)
ip_address = '216.239.36.21'
details = handler.getDetails(ip_address)
details.city
'Mountain View'
details.country
'US'
details.loc
'37.3861,-122.0840'

https://github.com/airakesh/BeautifulSoupRecipes/blob/master/geoip.py

# Get Geolocation(Country) and hostname by passing a file having a bunch of IP addresses as the argument from the command line. Example- python GeoIP.py path-to-file-containing-IP addresses:
https://github.com/airakesh/BeautifulSoupRecipes/blob/master/sample_ips.txt

import re
import os
import sys
import subprocess
import socket

# Input file argument
ips_file = sys.argv[1]

# The regular expression for validating an IP-address                                                                                                                                                            
pattern = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'''

def getGeoHost():
    fp = open(ips_file, 'rb')
    for line in fp:
        line = line.strip()
        addr = line.decode('utf-8')
        regex = re.compile(pattern)
        match = regex.match(addr)
        # Get hostname by IP address                                                                                                                                                                          
        try:
            host = socket.gethostbyaddr(addr)
            hostname = host[0]
        # Print Unknown no hostname is available                                                                                                                                                                  
        except:
            hostname = 'Unknown'

        # Get geolocation by IP address                                                                                                                                                                            
        get_geo_cmd = 'geoiplookup ' + addr
        geo_str = subprocess.check_output(get_geo_cmd, shell=True)
        geo = geo_str.decode('utf-8')

        # Match country name pattern                                                                                                                                                                              
        geo_pattern = '''^(GeoIP Country Edition: ([A-Z]{2})\, (.*))'''
        geo_regex = re.compile(geo_pattern)
        country_match = re.match(geo_pattern, geo)
        # Check country name is available and if not, print 'Unknown'                                                                                                                                               
        if country_match != '' and geo_pattern:
            try:
                country = country_match.group(3)
            except:
                country = 'Unknown'
        # Clubbing together in format 'IP|Country|Hostname' data                                                                                                                                                    
        geo_hostname = addr + ' | ' + country + ' | ' + hostname
        print geo_hostname


if __name__ == "__main__":

    ips_detail_list = getGeoHost()

您可以使用 ipinfo 的 api 首先訪問ipinfo.io並注冊。 您將獲得訪問令牌,復制它,現在執行pip install ipinfo現在您可以鍵入以下示例代碼:

>>> import ipinfo
>>> handler = ipinfo.getHandler(access_token)
>>> d = handler.getDetails(ip_address)
>>> d.city

或者,如果您直接執行d.details它將返回一個字典,您也可以將其用作字典,它將包含所有內容,例如 IP 地址、城市、國家/地區、州等。您也可以像這樣使用它們d.country或位置d.loc ,如我所寫的城市, d.city

nmap --script ip-geolocation-geoplugin <target>
Script Output
| ip-geolocation-geoplugin:
| coordinates: 39.4208984375, -74.497703552246
|_location: New Jersey, United States

https://nmap.org/nsedoc/scripts/ip-geolocation-geoplugin.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM