python小脚本——乱序IP按照IP段分类

2018-04-07 19:30:35 31 15953

0X00 背景

在甲方公司安全部门,经常迎接上级部门的安全检查。上级部门时不时给扔一堆某扫描器导出的报告,IP大概约有400-500左右。苦逼的要一个个IP查找所属IP段,然后转发给业务部门整改。这活一做就是一天,整个人都不好了。抽空一边百度一边写了一个分类IP的小脚本,和大家分享。

0x01 代码

使用了IP地址处理模块IPy,对IP地址处理起来方便很多。

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

from IPy import IP
import os
from sys import argv
import optparse  
import sys




def get_wenti_ip_list(file_name):             #从文件读取问题ip列表,每行一个Ip
    fp_wenti_ip = open(file_name,"r")
    value = 0
    ip_list = fp_wenti_ip.readlines()
    for wenti_ip in ip_list:
       wenti_ip = wenti_ip.strip('\n')
       ip_list[value] = wenti_ip
       value = value+1


    fp_wenti_ip.close()
    return ip_list




def get_zichan_ip_list(file_name,ip_list):            #从文件读取IP段列表,要求每一行仅一个IP段,中间用分号隔开
    fp_zichan = open(file_name,"r")
    fp_last = open("end.txt","w")
    new_ip_list = ip_list 


    zichan_IP_list = fp_zichan.readlines()   
    for zichan_ip in zichan_IP_list:
       zichan_ip = zichan_ip.split(';')
       zichan_ip[-1] = zichan_ip[-1].strip('\n') #按照每行来读,处理掉换行符
       for ip in new_ip_list:
         if (IP(ip) >= IP(zichan_ip[-2])) and (IP(ip) <= IP(zichan_ip[-1])): #比较IP是否在某一个段内,如果满足要求,写入最后生成的文件中
          fp_last.write(zichan_ip[0])
          fp_last.write(' ')
          fp_last.write(ip)
          fp_last.write('\n')



    fp_zichan.close()
    fp_last.close()



if __name__ == '__main__':
    parser = optparse.OptionParser(usage = '"usage: %prog problem.txt sources.txt"',version="%prog 1.0")
    default_encoding="utf-8"   #使用utf-8编码,解决中文乱码
    if(default_encoding!=sys.getdefaultencoding()):
       reload(sys)
       sys.setdefaultencoding(default_encoding)
    (options,args) = parser.parse_args()  #参数提示
    if len(args) < 1:
       parser.print_help()
       exit(0)

    wenti_ip_list = get_wenti_ip_list(argv[1])
    get_zichan_ip_list(argv[2],wenti_ip_list)

0x02 使用准备

参数中的problem.txt,为需要分类的IP列表,每行一个IP地址; 参数中的sources.txt,为各业务系统的IP段划分表,每行一个IP段,用分号隔开, 例如: A系统;10.1.1.1;10.1.1.255 B系统;10.1.2.1;10.1.2.255 ......

最终保存的分类好的IP保存在同目录下的end.txt

效果图:(涉及我司的公网IP地址,自知各位大佬厉害,就打码了。。。)

ps:小菜初学写脚本,只实现了功能,暂未考虑容错。欢迎各位大佬拍砖!

5ecurity团队成员tomcat([email protected])原创发布

原文链接:http://www.5ecurity.cn/index.php/archives/173/

关于作者

5ecurity18篇文章59篇回复

评论31次

要评论?请先  登录  或  注册