踩坑
本來我的win10里沒有安裝nmap,我直接pip install python-nmap安裝了python-nmap模塊,導致的最終結果就是報錯,沒有nmap二進制文件。
解決辦法,去http://nmap.org/dist/下載nmap安裝,在環境變量中添加安裝nmap的路徑(應該軟件自動就給辦了)。
然后就正常了。
編寫端口掃描器
掃描192.168.0.189的1-1000的開放情況。
>>> import nmap //引入nmap模塊
>>> nm=nmap.PortScanner() //實例化
>>> nm.scan('192.168.0.189','1-1000') //掃描192.168.0.189的1-1000端口
>>> for host in nm.all_hosts(): //遍歷主機
... print('-------------------------------------------')
... print('Host:%s(%s)'%(host,nm[host].hostname())) //主機名
... print('State:%s'%nm[host].state()) //主機狀態
... for proto in nm[host].all_protocols(): //遍歷協議
... print('-------------------------------------------')
... print('Protocol:%s'%proto) //輸出協議類型
... lport=nm[host][proto].keys() //獲取協議的所有掃描端口
... lport.sort() //端口列表排序
... for port in lport: //遍歷端口及輸出狀態
... print('port:%s\t state:%s'%(port,nm[host][proto][port]['state']))
命令行模式麻煩且不能糾錯,因此寫到e:// 1.py,然后cmd執行。(我試了試好像只能掃本機,別的好像要鏈接上才能掃)
掃描網段有哪些機器
import nmap
nm=nmap.PortScanner()
nm.scan(hosts='192.168.0.1/24',arguments='-sP') //ping主機在先掃描網段
hosts_list=[(x,nm[x]['status']['state']) for x in nm.all_hosts()] //保存主機狀態
for host,status in hosts_list: //遍歷主機名
print(host+" is "+status) //輸出主機名和狀態
異步掃描
import nmap
nma=nmap.PortScannerAsync() //支持異步掃描的函數
def callback_result(host,scan_result): //新定義
print '-------------------------------'
print host,scan_result //輸出主機名和掃描結果
nma.scan(hosts='192.168.0.1/24',arguments='-sP',callback=callback_result)
會返回掃描的結果。