<无详细内容>
标签: <无>
代码片段(1)[全屏查看所有代码]
1. [代码][Python]代码
01 | #!/usr/bin/env python |
02 | # -*- coding: utf-8 -*- |
03 | #查找IP地址归属地 |
04 | #writer by keery_log |
05 | #Create time:2013-10-30 |
06 | #Last update:2013-10-30 |
07 | #用法: python chk_ip.py www.google.com |python chk_ip.py 8.8.8.8 |python chk_ip.py ip.txt |
08 |
09 | 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" ][ "isp" ] |
34 |
35 | #定义IP与域名正则 |
36 | 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]?)$' ) |
37 | 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})+\.?' ) |
38 |
39 | if os.path.isfile(sys.argv[ 1 ]): #如果参数是文件,迭代查找 |
40 | file_path = sys.argv[ 1 ] |
41 | fh = open (file_path, 'r' ) |
42 | for line in fh.readlines(): |
43 | if re_ipaddress.match(line): |
44 | city_address = ip_location(line) |
45 | print line.strip() + ":" + city_address |
46 | else : |
47 | ip_address = sys.argv[ 1 ] |
48 | if re_ipaddress.match(ip_address): #如果参数是单个IP地址 |
49 | city_address = ip_location(ip_address) |
50 | print ip_address + ":" + city_address |
51 | elif (re_domain.match(ip_address)): #如果参数是域名 |
52 | result = socket.getaddrinfo(ip_address, None ) |
53 | ip_address = result[ 0 ][ 4 ][ 0 ] |
54 | city_address = ip_location(ip_address) |
55 | print ip_address.strip() + ":" + city_address |
举报