首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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

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)

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)

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:小菜初学写脚本,只实现了功能,暂未考虑容错。欢迎各位大佬拍砖!

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180407G144XU00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券