滲透測試經常需要進行針對目標主機IP地址段的各主機的端口進行掃描,然後輸出目標主機的開放端口的狀態。現利用nmap-python模塊編寫一個掃描腳本程序。代碼如下:
# 導入nmap模塊
import nmap
# 定義findTgts函數,參數為subNet(目標子網), portLst(目標端口列表)
def findTgts(subNet, portLst):
# 實例化nmap對象
nmScan = nmap.PortScanner()
# 遍歷目標端口
for port in portLst:
nmScan.scan(subNet, str(port))
# 建立一個目標主機空列表
tgtHosts = []
for host in nmScan.all_hosts():
if nmScan[host].has_tcp(port):
# 獲取目標主機tcp協議的目標端口的狀態
state = nmScan[host]['tcp'][port]['state']
# 判斷端口狀態是否開放
if state == 'open':
print('[+] Found Target Host: ' + host + ' ' + 'port: ' + str(port) + ' open')
tgtHosts.append(host)
return tgtHosts
if __name__ == '__main__':
portLst = [21, 22, 25, 445]
tgthosts = findTgts('192.168.31.33-240', portLst)
print(tgthosts)
針對目標IP地址段(192.168.31.33-240)端口(21,22, 25, 445)進行掃描,結果如下所示:
[+] Found Target Host: 192.168.31.82 port: 21 open
[+] Found Target Host: 192.168.31.82 port: 22 open
[+] Found Target Host: 192.168.31.113 port: 445 open
[+] Found Target Host: 192.168.31.192 port: 445 open
['192.168.31.82', '192.168.31.113', '192.168.31.192']
Process finished with exit code 0
I am a knock 7 year python The