使用python进行IP网段归属地查询

需提前安装好IPy,requests第三方库

pip install IPy
pip install requests

程序逻辑:先将IP段进行拆解为列表,随机取列表里面的IP进行归属地查询

代码如下:(注释的地方为多进程版本,需全部取消注释才可进行多进程运行,~多进程版本结果是无序的~)

# -*- coding: utf-8 -*-
# coding=utf-8
import IPy
import requests
import json
import sys
from multiprocessing import Pool
import random

reload(sys);
sys.setdefaultencoding("utf-8")

def select_addr(line,dstip):
   url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=%s&co=&resource_id=6006&t=1558517327933&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery1102004059669965615664_1558517308920&_=1558517"
   try:
       resp = requests.get(url % dstip, timeout=5)
       tmp = resp.text.split("(")[1].split(")")[0]
       tmp = json.loads(tmp)
       addr = tmp["data"][0]["location"].decode("utf-8")
       txt = str(line)+'\t'+str(dstip)+'\t'+addr
       return txt
   except Exception as e:
       print(e)
       return line+'\t'+dstip+'\t'+'select addr ERROR!'

def write_to_txt(addr):
   with open(save_file, 'a+') as fw:
       txt =  str(addr)
       print(txt)
       fw.write(txt + '\n')

if __name__ == "__main__" :
   ips_file = "E:/Desktop/get_addr/yd2.txt"          #IP段文件
   save_file = "E:/Desktop/get_addr/yd2_addr.txt"    #程序运行后保存结果文件
   #pool = Pool(8)  #多线程池关闭
   ips_dict = {}
   with open(ips_file,'r+') as fr:
           for line in fr:
               if len(line)>6:
                   line  = line.strip('\r').strip('\n').decode("utf-8")
                   try:
                       ips = IPy.IP(line, make_net=True)
                   except Exception as e:
                       print e
                       print 'ERROR:'+line
                       continue
                   dstip = ips[(random.randint(1,len(ips)-1))]
                   write_to_txt(select_addr(line,dstip))
                   #pool.apply_async(select_addr, (line,dstip,), callback=write_to_txt)  #多线程关闭
               else:
                   continue
           #pool.close()  #多线程关闭
           #pool.join()  #多线程关闭

脚本运行结果图:
IP网段进行归属地查询_线程池