腳本如下,需要用到IPy模塊,python-nmap模塊,腳本執(zhí)行后,以csv文檔將結(jié)果輸出到屏幕上
10年積累的網(wǎng)站建設(shè)、成都做網(wǎng)站經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先做網(wǎng)站設(shè)計后付款的網(wǎng)站建設(shè)流程,更有進(jìn)賢免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
#!/usr/bin/env python3
'''
參考鏈接 https://blog.csdn.net/qq_36119192/article/details/83717690
使用方法:
nmap_scan.py 192.168.0.0/24 22,3389
支持單個IP,網(wǎng)段掃描
網(wǎng)段格式支持:192.168.0.0/24,192.168.0.0/24
需要掃描的端口用逗號分隔
使用grep 過濾結(jié)果
grep -E '22|3389'
'''
import sys
import nmap
from IPy import IP
if len(sys.argv) != 3:
print("參數(shù)錯誤,支持格式:單個IP,后綴或掩碼形式的網(wǎng)段")
exit(1)
scan_ip = IP(sys.argv[1])
scan_port = sys.argv[2]
# scan_ip.prefixlen()
# 將網(wǎng)段轉(zhuǎn)所后綴形式
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 = []
# ports_list_len = 0
for port in ports:
if tcp[port]["state"] == "open":
ports_list.append("{}".format(port))
# ports_list_len += 1
else:
ports_list.append("")
# if ports_list_len != 0:
# print("{},{},{}".format(host, mac, ",".join(ports_list)))
print("{},{},{}".format(host, mac, ",".join(ports_list)))