一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術(shù)及教程分享平臺!
分類導(dǎo)航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務(wù)器之家 - 腳本之家 - Python - python 實現(xiàn)全球IP歸屬地查詢工具

python 實現(xiàn)全球IP歸屬地查詢工具

2021-08-15 11:45月為暮 Python

這篇文章主要介紹了python 實現(xiàn)全球IP歸屬地查詢工具的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# 寫在前面,這篇文章的原創(chuàng)作者是Charles我只是在他這個程序的基礎(chǔ)上邊進行加工,另外有一些自己的改造
# 并都附上了注釋和我自己的理解,這也是我一個學(xué)習(xí)的過程。
# 附上大佬的GitHub地址:https://github.com/CharlesPikachu/Tools
 
'''
Function:
  根據(jù)IP地址查其對應(yīng)的地理信息
Author:
  Charles
微信公眾號:
  Charles的皮卡丘
'''
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
  # 需要自己去這個網(wǎng)址注冊賬號,然后進行調(diào)用。
  # 這里我們先進行定義url
  host = 'https://ips.market.alicloudapi.com'
  path = '/iplocaltion'
  method = "GET"
  appcode = '填寫你自己的xxx'
  url = host + path + '?ip=' + ip
  # 定義頭部。
  headers = {"Authorization": 'APPCODE ' + appcode}
  try:
   # 進行獲取調(diào)用結(jié)果。
   rep = requests.get(url, headers=headers)
  except:
   return 'url參數(shù)錯誤'
  # 判斷是否調(diào)用成功。如果調(diào)用成功就接著進行下邊的動作。
  httpStatusCode = rep.status_code
  if httpStatusCode == 200:
   # 轉(zhuǎn)換成json格式
   data = rep.json()
   # 然后獲取其中的參數(shù)。
   ''''
   # 是以下邊這種格式進行返回的。
   {
     "code": 100,
     "message": "success",
     "ip": "110.188.234.66",
     "result": {
          "en_short": "CN", // 英文簡稱
     "en_name": "China", // 歸屬國家英文名稱
   "nation": "中國", // 歸屬國家
   "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國家: %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ù)錯誤"
   elif (httpStatusCode == 400 and httpReason == 'Invalid AppCode'):
     return "AppCode錯誤"
   elif (httpStatusCode == 400 and httpReason == 'Invalid Url'):
     return "請求的 Method、Path 或者環(huán)境錯誤"
   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)錯誤"
   else:
     return "參數(shù)名錯誤 或 其他錯誤" + httpStatusCode + httpReason
 
  return result
 
'''淘寶API'''
def getTaobaoIP(ip):
  # 請求淘寶獲取IP位置的API接口,但是現(xiàn)在有些不是很好用了。查不出來了。
  # 看了看接口需要進行傳入秘鑰
  url = 'http(s)://ips.market.alicloudapi.com/iplocaltion'
  # 使用get方法進行請求。
  res = requests.get(url+ip, headers=headers)
  # 然后進行解析參數(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國家: %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國家: %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()
  # 實例化一個有道翻譯的類。
  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國家: %s\n地區(qū): %s\n城市: %s\n''' % (ip, longitude, latitude, continent_name, country_name, region_name, city) \
  + '-'*50
  return result
 
 
'''IP地址有效性驗證'''
def isIP(ip):
  try:
   IPy.IP(ip)
   return True
  except:
   return False
 
 
'''
Function:
  有道翻譯類,進行翻譯上邊我們查詢結(jié)果的返回值。
'''
class youdao():
  def __init__(self):
   # 這里我們需要使用post方法進行調(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 =
  # 進行翻譯。
  def translate(self, word):
   # 先判斷單詞是否為空。
   if word is None:
     return [word]
   # 隨機生成一個時間。
   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()
   # 進行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)用幾個接口進行查詢。
   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)ⅰ?/code>
  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
  # 判斷終端是否有進行輸入?yún)?shù)。
  if ip:
   main(ip)
  if filename:
   with open(filename) as f:
     # 獲取文件中的所有IP地址,存放成一個列表的形式。
     ips = [ip.strip('\n') for ip in f.readlines()]
   for ip in ips:
     main(ip)

PS:推薦一款在線工具ip地址查詢:https://tool.zzvips.com/t/ip/

以上就是python 實現(xiàn)全球IP歸屬地查詢工具的詳細內(nèi)容,更多關(guān)于python ip歸屬地查詢的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!

原文鏈接:https://www.cnblogs.com/cong12586/p/14143727.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 外国老少性配 | 日本不卡在线观看免费v | 免费yjsp妖精com | 北条麻妃黑人正在播放 | segui久久综合精品 | 青青青国产视频 | 国产一区二区三区久久精品小说 | 天天操免费视频 | 大胸孕妇孕交pregnantsex 大象视频污 | 99rv精品视频在线播放 | 四虎成人免费 | 高清国产欧美一v精品 | 1024免费福利永久观看网站 | 国产精品久久国产精品99 gif | 男女羞羞的视频 | 精品视频在线免费 | 四虎传媒| 色偷偷91久久综合噜噜噜 | 亚洲国产欧美目韩成人综合 | 玩高中女同桌肉色短丝袜脚文 | 色噜噜国产精品视频一区二区 | www日本在线观看 | 成人一级黄色大片 | 3p文两男一女办公室高h | 扒开黑女人p大荫蒂老女人 扒开大腿狠狠挺进视频 | 99精品国产高清自在线看超 | 国产123区 | 亚洲免费高清视频 | 国产精品一级片 | 国产精品美女久久久久网站 | 亚洲 欧美 国产 综合首页 | 挺进白嫩老师下面视频 | 色综合视频在线 | 精品国产影院 | 人与动人物人a级特片 | 精品AV综合导航 | 日本妇人成熟免费不卡片 | 男女啪啪gif | 亚洲日本久久一区二区va | 日本午夜影院 | 青草草在线观看 |