#!/usr/bin/env python#-*-coding:utf-8-*-#查找IP地址归属地 #writer by keery_log#create time:2013-10-30#last Update : 2013-10-30# usage: python chk_ip.py www.google.com |python chk_ip.py 8.8.8.8 |python chk_ip.py ip.txt import signalimport URL Libimport jsonimport sys,os,reimport Socket If Len (sys.argv) <= 1:print "Please input IP address!" Sys.exit (0) def handler (Signum, frame): Sys.exit (0) signal.signal (signal. SIGINT, handler) URL = "http://ip.taobao.com/service/getIpInfo.php?ip=" #查找IP地址def ip_location (IP): data = Urllib.urlo Pen (url + IP). Read () datadict=json.loads (data) for Oneinfo in Datadict:if "code" = = Oneinfo:if Datadict[oneinfo] = = 0:return datadict["Data" ["country"] + datadict["Data" ["region"] + datadict["Data" [ "City"] + datadict["Data" [ISP] #定义IP与域名正则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]?) $ ') 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}) +\.? ') If Os.path.isfile (Sys.argv[1]): #如果参数是文件, iterative lookup file_path = sys.argv[1] fh = open (File_path, ' R ') for line in Fh.re Adlines (): If Re_ipaddress.match (line): city_address = ip_location (line) print Line.strip () + ":" + city_addresselse:ip_address = sys.argv[1] If Re_ipaddress.match (ip_address): #如果参数是单个IP地址 city_addre SS = Ip_location (ip_address) print IP_Address + ":" + city_address elif (Re_domain.match (ip_address)): #如果参数是域名 result = Socket.getaddrinfo (IP_Address, None) ip_address = result[0][4][0] City_address = ip_location (ip_address) Print ip_address.strip () + ":" + city_address
Python IP address query attribution