当前位置: 首页 > news >正文

告别手动整理!用Python脚本调用Eeyes实现自动化C段资产梳理

用Python脚本调用Eeyes实现自动化C段资产梳理

在安全运维和DevSecOps领域,资产梳理是基础但极其重要的工作。传统手动整理C段资产的方式不仅效率低下,还容易遗漏关键信息。本文将介绍如何通过Python脚本调用Eeyes工具,实现自动化C段资产梳理,提升安全运维效率。

1. 环境准备与工具介绍

在开始自动化脚本开发前,需要准备好基础环境。Eeyes是一款专注于从大量域名中提取真实IP并整理为C段的工具,特别适合在红蓝对抗和外部攻击面管理(EASM)场景中使用。

基础环境要求

  • Python 3.6+
  • Eeyes工具(可从官方仓库获取)
  • 网络访问权限(用于域名解析)

安装必要的Python依赖:

pip install requests subprocess32 pandas

Eeyes的主要功能特点:

  • 支持从文件批量读取域名
  • 自动识别CDN并获取真实IP
  • 将IP整理为C段格式输出
  • 可生成日志文件便于后续分析

2. Eeyes基础功能封装

首先,我们需要用Python封装Eeyes的基础功能,使其可以通过脚本调用。这里我们使用subprocess模块来调用命令行工具。

import subprocess import os class EeyesWrapper: def __init__(self, eeyes_path): self.eeyes_path = eeyes_path def scan_domains_from_file(self, input_file, output_file=None): """从文件读取域名进行扫描""" cmd = [self.eeyes_path, '-l', input_file] if output_file: cmd.extend(['-log', output_file]) try: result = subprocess.run( cmd, capture_output=True, text=True, check=True ) return result.stdout except subprocess.CalledProcessError as e: print(f"Eeyes执行失败: {e.stderr}") return None

这个基础封装类提供了从文件读取域名进行扫描的功能。在实际使用中,你可以根据需要扩展更多功能,比如直接扫描单个域名或处理特殊格式的输入。

3. 输出结果解析与处理

Eeyes的输出结果需要进一步处理才能生成结构化的C段资产报告。下面是一个结果解析器的实现示例:

import re from collections import defaultdict import ipaddress class EeyesResultParser: def __init__(self): self.ip_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b') def parse_to_c_blocks(self, eeyes_output): """将Eeyes输出解析为C段分类""" ips = self._extract_ips(eeyes_output) c_blocks = defaultdict(list) for ip in ips: try: network = ipaddress.IPv4Network(f"{ip}/24", strict=False) c_block = str(network.network_address) c_blocks[c_block].append(ip) except ValueError: continue return c_blocks def _extract_ips(self, text): """从文本中提取所有IP地址""" return self.ip_pattern.findall(text)

使用这个解析器,我们可以将Eeyes的输出转换为更有组织的C段资产数据:

# 使用示例 wrapper = EeyesWrapper('path/to/eeyes') result = wrapper.scan_domains_from_file('domains.txt') parser = EeyesResultParser() c_blocks = parser.parse_to_c_blocks(result) for c_block, ips in c_blocks.items(): print(f"C段 {c_block}/24 包含IP: {', '.join(ips)}")

4. 自动化流程设计与优化

要实现完整的自动化资产梳理流程,我们需要考虑以下几个关键点:

  1. 输入处理:支持多种输入来源(文件、API、数据库等)
  2. 扫描执行:稳定调用Eeyes进行扫描
  3. 结果解析:提取并结构化C段信息
  4. 报告生成:输出易读的报告
  5. 异常处理:应对网络波动等异常情况

完整自动化流程示例

import time import json from datetime import datetime class CBlockAutomation: def __init__(self, eeyes_path): self.eeyes = EeyesWrapper(eeyes_path) self.parser = EeyesResultParser() def run_automation(self, input_source, output_format='json'): """执行完整的自动化流程""" # 1. 准备输入 domains = self._prepare_input(input_source) # 2. 执行扫描 scan_result = self._execute_scan(domains) # 3. 解析结果 c_blocks = self.parser.parse_to_c_blocks(scan_result) # 4. 生成报告 report = self._generate_report(c_blocks, output_format) return report def _prepare_input(self, source): """准备输入数据""" if isinstance(source, list): return source elif os.path.isfile(source): with open(source) as f: return [line.strip() for line in f if line.strip()] else: raise ValueError("不支持的输入类型") def _execute_scan(self, domains): """执行Eeyes扫描""" temp_file = f"temp_domains_{int(time.time())}.txt" try: with open(temp_file, 'w') as f: f.write('\n'.join(domains)) return self.eeyes.scan_domains_from_file(temp_file) finally: if os.path.exists(temp_file): os.remove(temp_file) def _generate_report(self, c_blocks, format): """生成报告""" if format == 'json': return json.dumps(c_blocks, indent=2) elif format == 'text': report = [] for c_block, ips in c_blocks.items(): report.append(f"C段 {c_block}/24 (共{len(ips)}个IP):") report.extend(f" - {ip}" for ip in sorted(ips)) report.append("") return '\n'.join(report) else: raise ValueError("不支持的输出格式")

5. 高级功能与实战技巧

在实际使用中,我们还需要考虑一些高级功能和优化技巧:

5.1 处理网络波动问题

网络不稳定可能导致Eeyes识别率下降。我们可以实现重试机制:

def execute_scan_with_retry(self, domains, max_retries=3): """带重试机制的扫描执行""" for attempt in range(max_retries): try: result = self._execute_scan(domains) if result and self._validate_result(result): return result except Exception as e: print(f"扫描失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}") time.sleep(5 * (attempt + 1)) raise RuntimeError("扫描失败,达到最大重试次数") def _validate_result(self, result): """验证扫描结果是否有效""" return len(self.parser._extract_ips(result)) > 0

5.2 与资产管理系统集成

将自动化脚本与现有资产管理系统集成可以进一步提升效率:

def upload_to_asset_management(self, c_blocks, api_endpoint): """将C段资产上传到资产管理系统""" payload = { "timestamp": datetime.now().isoformat(), "c_blocks": [ { "network": f"{c_block}/24", "ips": ips, "count": len(ips) } for c_block, ips in c_blocks.items() ] } response = requests.post( api_endpoint, json=payload, headers={'Content-Type': 'application/json'} ) if response.status_code != 200: raise RuntimeError(f"上传失败: {response.text}") return response.json()

5.3 定时任务与无人值守运行

使用Python的schedule库可以实现定时自动运行:

import schedule def schedule_daily_scan(input_file, output_dir): """设置每日自动扫描任务""" automation = CBlockAutomation('path/to/eeyes') def job(): date_str = datetime.now().strftime("%Y%m%d") output_file = os.path.join(output_dir, f"c_blocks_{date_str}.json") report = automation.run_automation(input_file, 'json') with open(output_file, 'w') as f: f.write(report) print(f"扫描完成,结果已保存到 {output_file}") # 每天凌晨2点执行 schedule.every().day.at("02:00").do(job) while True: schedule.run_pending() time.sleep(60)

6. 性能优化与最佳实践

为了确保脚本在大规模资产梳理场景下的性能,可以考虑以下优化措施:

  1. 批量处理:将域名分批处理,避免一次性处理过多导致内存问题
  2. 并行扫描:使用多进程加速扫描过程
  3. 结果缓存:缓存已扫描的域名结果,避免重复工作
  4. 日志记录:详细记录操作日志,便于问题排查

并行扫描实现示例

from multiprocessing import Pool def parallel_scan(domains, eeyes_path, workers=4): """并行扫描域名""" chunk_size = (len(domains) + workers - 1) // workers chunks = [ domains[i:i+chunk_size] for i in range(0, len(domains), chunk_size) ] with Pool(workers) as pool: results = pool.starmap( scan_chunk, [(chunk, eeyes_path) for chunk in chunks] ) return '\n'.join(filter(None, results)) def scan_chunk(domains, eeyes_path): """扫描一批域名""" temp_file = f"temp_{os.getpid()}.txt" try: with open(temp_file, 'w') as f: f.write('\n'.join(domains)) wrapper = EeyesWrapper(eeyes_path) return wrapper.scan_domains_from_file(temp_file) finally: if os.path.exists(temp_file): os.remove(temp_file)

在实际项目中,根据域名数量和服务器资源情况调整worker数量,通常设置为CPU核心数的2-4倍效果最佳。

http://www.jsqmd.com/news/913543/

相关文章:

  • 一套可直接编译运行的C语言指纹识别全流程代码,含测试图与格式读写支持
  • 微前端架构:现代前端架构新趋势
  • 别再傻傻分不清了!用5分钟搞懂机器学习里的TP、FP、TN、FN(附实战案例)
  • Cesium加载SuperMap WMTS100服务报400?别慌,可能是这个XML节点顺序的坑
  • 2026年最值得投入的AI岗位:零基础转行AI训练师,我只看这一套课!
  • 多因子股票预测实战代码包:随机森林回测+单因子筛选+分类可视化图表
  • stm32-SPI
  • 实时库存准确率从82%跃升至99.6%,Lindy自动化配置清单,含7个不可跳过的校验节点
  • 别再傻傻分不清了!Unity编辑器开发中EditorWindow、Editor、PropertyDrawer到底怎么选?
  • 电路设计实战:从元器件选型到PCB制作与调试全流程解析
  • 用遗传算法自动找LQR最优Q和R矩阵,MATLAB一键跑通闭环仿真
  • Arduino实时时钟RTC模块DS3231应用指南:从硬件连接到代码实现
  • 智驱监管 无感赋能|黎阳之光人员无感技术升级海关旅检模式
  • 揭秘Anthropic最新融资路演PPT:8个被刻意隐藏的数据陷阱,90%技术决策者已踩坑
  • 免费在线3D查看器终极指南:浏览器中轻松预览和测量任何3D设计文件
  • 告别CAN总线8字节限制:手把手教你用AUTOSAR CanTp模块搞定ISO 15765长报文传输
  • 基于Arduino与多传感器的手语翻译手套:从硬件搭建到算法实现
  • STM32F103用W5500直连OneNet做远程温控与继电器开关,带全套KEIL工程和驱动源码
  • Anthropic CLI(Claude Code)启动报错 422 完整解决办法
  • WindowResizer技术指南:使用Windows API实现窗口强制调整的完整解决方案
  • 【语音】笔记
  • 保姆级教程:用MIM搞定MMSegmentation v1.1.0 + MMCV 2.0.0rc4的完整安装流程(附CUDA 11.1环境检查)
  • 明穆宗 朱载坖
  • MindSpore Transformers 断点续训功能原理
  • 旅游管理毕设实战包:SpringBoot后端+Vue前端,含可运行源码、万字论文文档、部署教程与答辩PPT
  • 双FA自动耦合:从技术原理到量产效能飞跃
  • 儿童电动车辅助开关与PVC支撑框架改装指南:为特殊需求儿童打造专属座驾
  • 为什么我的频谱图纵坐标是负的?从dB/Hz单位聊聊信号处理中的对数变换
  • Claude用户手册制作(含可复用的Figma交互原型+Notion自动化工作流)
  • 安达发|电线电缆行业aps自动排产:从人工排程之困到智能驱动之变