The python module using nmap scan host-generated csv file

Script as follows, we need to use IPy module, python-nmap module, the script execution to csv document output to the screen

#!/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)))

Guess you like

Origin blog.51cto.com/penguintux/2429126