溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用python怎么對(duì)IP歸屬地進(jìn)行查詢

發(fā)布時(shí)間:2020-12-18 14:05:04 來源:億速云 閱讀:461 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)利用python怎么對(duì)IP歸屬地進(jìn)行查詢,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

import IPy
import time
import random
import hashlib
import argparse
import requests


headers = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}



def getaliIP(ip):
  # 這里使用ali的IP地址查詢功能。
  # https://market.aliyun.com/products/?keywords=ip%E5%BD%92%E5%B1%9E%E5%9C%B0
  # 需要自己去這個(gè)網(wǎng)址注冊(cè)賬號(hào),然后進(jìn)行調(diào)用。
  # 這里我們先進(jìn)行定義url
  host = 'https://ips.market.alicloudapi.com'
  path = '/iplocaltion'
  method = "GET"
  appcode = '填寫你自己的xxx'
  url = host + path + '?ip=' + ip
  # 定義頭部。
  headers = {"Authorization": 'APPCODE ' + appcode}
  try:
   # 進(jìn)行獲取調(diào)用結(jié)果。
   rep = requests.get(url, headers=headers)
  except:
   return 'url參數(shù)錯(cuò)誤'
  # 判斷是否調(diào)用成功。如果調(diào)用成功就接著進(jìn)行下邊的動(dòng)作。
  httpStatusCode = rep.status_code
  if httpStatusCode == 200:
   # 轉(zhuǎn)換成json格式
   data = rep.json()
   # 然后獲取其中的參數(shù)。
   ''''
   # 是以下邊這種格式進(jìn)行返回的。
   {
     "code": 100,
     "message": "success",
     "ip": "110.188.234.66",
     "result": {
          "en_short": "CN", // 英文簡(jiǎn)稱
     "en_name": "China", // 歸屬國(guó)家英文名稱
   "nation": "中國(guó)", // 歸屬國(guó)家
   "province": "四川省", // 歸屬省份
   "city": "綿陽市", // 歸屬城市
   "district": "涪城區(qū)", // 歸屬縣區(qū)
   "adcode": 510703, // 歸屬地編碼
   "lat": 31.45498, // 經(jīng)度
   "lng": 104.75708 // 維度
   }
   }'''
   result1 = data.get('result')
   city = result1['city']
   province = result1['province']
   nation = result1['nation']
   district = result1['district']
   latitude = result1['lat']
   longitude = result1['lng']
   # 返回我們需要的結(jié)果。
   result = '-' * 50 + '\n' + \
       '''[ali.com查詢結(jié)果-IP]: %s\n經(jīng)緯度: (%s, %s)\n國(guó)家: %s\n地區(qū): %s\n城市: %s\n''' % (
       ip, longitude, latitude, nation, province, city) \
       + '-' * 50
  else:
   httpReason = rep.headers['X-Ca-Error-Message']
   if (httpStatusCode == 400 and httpReason == 'Invalid Param Location'):
     return "參數(shù)錯(cuò)誤"
   elif (httpStatusCode == 400 and httpReason == 'Invalid AppCode'):
     return "AppCode錯(cuò)誤"
   elif (httpStatusCode == 400 and httpReason == 'Invalid Url'):
     return "請(qǐng)求的 Method、Path 或者環(huán)境錯(cuò)誤"
   elif (httpStatusCode == 403 and httpReason == 'Unauthorized'):
     return "服務(wù)未被授權(quán)(或URL和Path不正確)"
   elif (httpStatusCode == 403 and httpReason == 'Quota Exhausted'):
     return "套餐包次數(shù)用完"
   elif (httpStatusCode == 500):
     return "API網(wǎng)關(guān)錯(cuò)誤"
   else:
     return "參數(shù)名錯(cuò)誤 或 其他錯(cuò)誤" + httpStatusCode + httpReason

  return result

'''淘寶API'''
def getTaobaoIP(ip):
  # 請(qǐng)求淘寶獲取IP位置的API接口,但是現(xiàn)在有些不是很好用了。查不出來了。
  # 看了看接口需要進(jìn)行傳入秘鑰
  url = 'http(s)://ips.market.alicloudapi.com/iplocaltion'
  # 使用get方法進(jìn)行請(qǐng)求。
  res = requests.get(url+ip, headers=headers)
  # 然后進(jìn)行解析參數(shù)。
  data = res.json().get('data')
  print(res.json)
  if data is None:
   return '[淘寶API查詢結(jié)果-IP]: %s\n無效IP' % ip
  result = '-'*50 + '\n' + \
  '''[淘寶API查詢結(jié)果-IP]: %s\n國(guó)家: %s\n地區(qū): %s\n城市: %s\n''' % (ip, data.get('country'), data.get('region'), data.get('city')) \
  + '-'*50
  return result


'''ip-api.com(很不準(zhǔn))'''
def getIpapiIP(ip):
  url = 'http://ip-api.com/json/'
  res = requests.get(url+ip, headers=headers)
  data = res.json()
  yd = youdao()
  city = yd.translate(data.get('city'))[0][0]['tgt']
  country = yd.translate(data.get('country'))[0][0]['tgt']
  region_name = yd.translate(data.get('regionName'))[0][0]['tgt']
  latitude = data.get('lat')
  longitude = data.get('lon')
  result = '-'*50 + '\n' + \
  '''[ip-api.com查詢結(jié)果-IP]: %s\n經(jīng)緯度: (%s, %s)\n國(guó)家: %s\n地區(qū): %s\n城市: %s\n''' % (ip, longitude, latitude, country, region_name, city) \
  + '-'*50
  return result


'''ipstack.com'''
def getIpstackIP(ip):
  # 定義url
  url = 'http://api.ipstack.com/{}?access_key=1bdea4d0bf1c3bf35c4ba9456a357ce3'
  res = requests.get(url.format(ip), headers=headers)
  data = res.json()
  # 實(shí)例化一個(gè)有道翻譯的類。
  yd = youdao()
  # 調(diào)用翻譯函數(shù)。獲取翻譯的值。
  continent_name = yd.translate(data.get('continent_name'))[0][0]['tgt']
  country_name = yd.translate(data.get('country_name'))[0][0]['tgt']
  region_name = yd.translate(data.get('region_name'))[0][0]['tgt']
  city = yd.translate(data.get('city'))[0][0]['tgt']
  # 獲取經(jīng)緯度。
  latitude = data.get('latitude')
  longitude = data.get('longitude')
  result = '-'*50 + '\n' + \
  '''[ipstack.com查詢結(jié)果-IP]: %s\n經(jīng)緯度: (%s, %s)\n板塊: %s\n國(guó)家: %s\n地區(qū): %s\n城市: %s\n''' % (ip, longitude, latitude, continent_name, country_name, region_name, city) \
  + '-'*50
  return result


'''IP地址有效性驗(yàn)證'''
def isIP(ip):
  try:
   IPy.IP(ip)
   return True
  except:
   return False


'''
Function:
  有道翻譯類,進(jìn)行翻譯上邊我們查詢結(jié)果的返回值。
'''
class youdao():
  def __init__(self):
   # 這里我們需要使用post方法進(jìn)行調(diào)用接口。
   self.headers = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
   }

   self.data = {
        'i': 'hello',
        'action': 'FY_BY_CLICKBUTTION',
        'bv': 'e2a78ed30c66e16a857c5b6486a1d326',
        'client': 'fanyideskweb',
        'doctype': 'json',
        'from': 'AUTO',
        'keyfrom': 'fanyi.web',
        'salt': '15532627491296',
        'sign': 'ee5b85b35c221d9be7437297600c66df',
        'smartresult': 'dict',
        'to': 'AUTO',
        'ts': '1553262749129',
        'typoResult': 'false',
        'version': '2.1'
        }
   # 有道翻譯調(diào)用接口的url
   self.url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
   # http: // fanyi.youdao.com / translate?smartresult = dict & smartresult = rule & sessionFrom =
  # 進(jìn)行翻譯。
  def translate(self, word):
   # 先判斷單詞是否為空。
   if word is None:
     return [word]
   # 隨機(jī)生成一個(gè)時(shí)間。
   t = str(time.time()*1000 + random.randint(1,10))
   t = str(time.time()*1000 + random.randint(1, 10))
   # 傳入我們需要翻譯的單詞和其他參數(shù)。
   self.data['i'] = word
   self.data['salt'] = t
   sign = 'fanyideskweb' + word + t + '6x(ZHw]mwzX#u0V7@yfwK'
   # 這里需要哈希一下。
   self.data['sign'] = hashlib.md5(sign.encode('utf-8')).hexdigest()
   # 進(jìn)行post方法調(diào)用接口,并獲取我們需要的參數(shù)。
   res = requests.post(self.url, headers=self.headers, data=self.data)
   # 返回翻譯的結(jié)果。
   return res.json()['translateResult']


'''主函數(shù)'''
def main(ip):
  separator = '*' * 30 + 'IPLocQuery' + '*' * 30
  # 首先判斷IP地址是否合法。
  if isIP(ip):
   # 然后分別調(diào)用幾個(gè)接口進(jìn)行查詢。
   print(separator)
   print(getaliIP(ip))
   print(getIpstackIP(ip))
   print(getIpapiIP(ip))
   print('*' * len(separator))
  else:
   print(separator + '\n[Error]: %s --> 無效IP地址...\n' % ip + '*' * len(separator))
  

if __name__ == '__main__':
  # 獲取終端輸入的入?yún)ⅰ?
  parser = argparse.ArgumentParser(description="Query geographic information based on IP address.")
  # 可選參數(shù),代表著文件的名字,里邊存放著IP之地。
  parser.add_argument('-f', dest='filename', help='File to be queried with one ip address per line')
  # 可選參數(shù),代表著我們需要查詢的IP地址。
  parser.add_argument('-ip', dest='ipaddress', help='Single ip address to be queried')
  args = parser.parse_args()
  # 獲取終端輸入的參數(shù)。
  ip = args.ipaddress
  filename = args.filename
  # 判斷終端是否有進(jìn)行輸入?yún)?shù)。
  if ip:
   main(ip)
  if filename:
   with open(filename) as f:
     # 獲取文件中的所有IP地址,存放成一個(gè)列表的形式。
     ips = [ip.strip('\n') for ip in f.readlines()]
   for ip in ips:
     main(ip)

以上就是利用python怎么對(duì)IP歸屬地進(jìn)行查詢,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI