Python查詢IP地址歸屬完整代碼如下:
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #查找IP地址歸屬地
4 #writer by keery_log
5 #Create time:2013-10-30
6 #Last update:2013-10-30
7 #用法: python chk_ip.py www.google.com |python chk_ip.py 8.8.8.8 |python chk_ip.py ip.txt
8
9 import signal
10 import urllib
11 import json
12 import sys,os,re
13 import socket
14
15 if len(sys.argv) <= 1 :
16 print "Please input ip address !"
17 sys.exit(0)
18
19 def handler(signum, frame):
20 sys.exit(0)
21 signal.signal(signal.SIGINT, handler)
22
23 url = "http://ip.taobao.com/service/getIpInfo.php?ip="
24
25 #查找IP地址
26 def ip_location(ip):
27 data = urllib.urlopen(url + ip).read()
28 datadict=json.loads(data)
29
30 for oneinfo in datadict:
31 if "code" == oneinfo:
32 if datadict[oneinfo] == 0:
33 return datadict["data"]["country"] + datadict["data"]["region"] + datadict["data"]["city"] + datadict["data"]34 ["isp"]
35
36 #定義IP與域名正則
37 re_ipaddress = re.compile(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
38 re_domain = re.compile(r'[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?')
39
40 if os.path.isfile(sys.argv[1]): #如果參數是文件,迭代查找
41 file_path = sys.argv[1]
42 fh = open(file_path,'r')
43 for line in fh.readlines():
44 if re_ipaddress.match(line):
45 city_address = ip_location(line)
46 print line.strip() + ":" + city_address
47else:
48 ip_address = sys.argv[1]
49 if re_ipaddress.match(ip_address): #如果參數是單個IP地址
50 city_address = ip_location(ip_address)
51 print ip_address + ":" + city_address
52 elif(re_domain.match(ip_address)): #如果參數是域名
53 result = socket.getaddrinfo(ip_address, None)
54 ip_address = result[0][4][0]
55 city_address = ip_location(ip_address)
56 print ip_address.strip() + ":" + city_address
僅供參考