說明:藍色=命令名稱php
淺綠=命令參數html
淺藍=選項python
紫色=目錄json
系統環境:windows 7 32位windows
python版本:Python 2.7.3app
代碼以下:socket
- #!/usr/bin/env python
- #-*- coding:utf-8 -*-
- #Author:left_left
- import socket
- import json
- def json_info(data):
- data = json.loads(data)
- if data["code"]:
- return False
- else:
- return data["data"]
- def get_addr(ip):
- head_info = "GET /service/getIpInfo.php?ip=%s HTTP/1.1\r\n" % ip +\
- "Host:ip.taobao.com\r\n" +\
- "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0\r\n" +\
- "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n\r\n"
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- addr = socket.gethostbyname("ip.taobao.com")
- s.connect((addr, 80))
- s.send(head_info)
- info = s.recv(4096)
- json_data = info.split("\r\n")
- return json_info(json_data[-4])
- s.close()
- def ip_read():
- ip_f = open("./ip")
- for line in ip_f:
- ip = line.split("/")
- if len(ip)>1:
- info = get_addr(ip[0])
- if info:
- data = " ".join([line.strip("\n"), info["ip"], info["country"],
- info["city"],info["region"], info["area"], info["isp"]])
- print data
- else:
- print "%s error..." % line
- else:
- print line
- if __name__ == "__main__":
- ip_read()
ip文件內容以下:ide
- [北京-長城寬帶-BGP]
- 101.38.0.0/15
- 101.40.0.0/15
- 124.14.224.0/19
- 124.14.64.0/18
- 124.254.0.0/18
- 180.88.128.0/18
- 180.88.96.0/19
- 180.89.64.0/19
- 211.161.0.0/20
- 211.161.32.0/20
- 220.113.0.0/19
- 220.113.32.0/20
- 60.253.128.0/17
- [鵬博士-BGP]
- 1.93.0.0/16
- 101.247.128.0/18
- 113.44.0.0/16
- 113.45.0.0/16
- 113.46.0.0/16
- 113.47.0.0/16
結果如圖:spa