Python IP address query attribution

Source: Internet
Author: User

#!/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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.