1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import nmap3 import json import time import openpyxl import os import re
def gain_path(filename): """把文件名转成相对于脚本所在目录的绝对路径""" path_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(path_dir, filename)
def timer(func): def wrapper(*args, **kwargs): start_time = time.time() result=func(*args, **kwargs) end_time = time.time() print(f"{func.__name__}函数执行时间:{end_time - start_time}秒") return result return wrapper @timer def from_txt(file): filepath=gain_path(file) with open(filepath, 'r') as f: return [i.strip() for i in f.readlines() if i.strip()]
def ip_clean(ips): cleaned_ips=[] for i in ips: match = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', i) if not match: continue else: cleaned_ips.append(match.group()) return list(dict.fromkeys(cleaned_ips))
@timer def scan(ip): scaner=nmap3.Nmap() result=scaner.scan_top_ports(ip,default=100,args='-Pn -sV') return ip,result @timer def to_excel(ip,result,ws): scaned_ip=ip ip_datas = result[scaned_ip].get('ports',[]) for ip_data in ip_datas: protocol_data = ip_data.get('protocol','') port_data = ip_data.get('portid','') state_data = ip_data.get('state','') service_data = ip_data.get('service', {}).get('name', '') ws.append([scaned_ip,protocol_data,port_data,state_data,service_data])
def main(): try: wb=openpyxl.Workbook() ws=wb.active ws.append(['IP', '协议', '端口号', '状态', '服务']) filename=input("请输入ip文件名:").strip() ips=from_txt(filename) okips=ip_clean(ips) for ip in okips: scaned_result=scan(ip) status=to_excel(scaned_result[0],scaned_result[1],ws) wb.save(gain_path('scan_result.xlsx')) print("扫描完成!,结果已存储至scan_result.xlsx") except Exception as e: print(f"发生错误:{e}")
if __name__ == '__main__': main()
|