使用python的nmap模块扫描主机生成csv文档

脚本如下,需要用到IPy模块,python-nmap模块,脚本执行后,以csv文档将结果输出到屏幕上

#!/usr/bin/env python3

'''
参考链接 https://blog.csdn.net/qq_36119192/article/details/83717690
使用方法:
nmap_scan.py 192.168.0.0/24 22,3389
支持单个IP,网段扫描
网段格式支持:192.168.0.0/24,192.168.0.0/24
需要扫描的端口用逗号分隔
'''

import sys
import nmap
from IPy import IP

if len(sys.argv) != 3:
    print("参数错误,支持格式:单个IP,后缀或掩码形式的网段")
    exit(1)

scan_ip = IP(sys.argv[1])
scan_port = sys.argv[2]

# scan_ip.prefixlen()
scan_ip = "{}".format(scan_ip)

for port in [ int(i) for i in scan_port.split(",") ]:
    if port < 1 or port >  65535:
        print("端口范围 1 - 65535")
        exit(1)

nm=nmap.PortScanner()
nm.scan(scan_ip, scan_port,'-Pn')
hosts = nm.all_hosts()
for host in hosts:
    mac = nm[host]["addresses"].get("mac", "")
    tcp = nm[host]["tcp"]
    ports = nm[host]["tcp"].keys()
    ports_list = []
    for port in ports:
        if tcp[port]["state"] == "open":
            ports_list.append("{}".format(port))
        else:
            ports_list.append("")
    print("{},{},{}".format(host, mac, ",".join(ports_list)))
上一篇:packetbeat 7.1.1对nginx流量的采集及对http协议的解析配置


下一篇:Java – 端口侦听程序的漏洞有哪些?