1. 程式人生 > >端口掃描nmap

端口掃描nmap

nmap

#!/usr/bin/python3

-- coding:utf-8 --

import sys
import nmap

scan_row = []
input_data = input(‘Please input hosts and port: ‘)
scan_row = input_data.split(" ")
if len(scan_row) != 2:
print("Input errors,example \"192.168.1.0/24 80,443,22\"")
sys.exit(0)
hosts = scan_row[0] # 接收用戶輸入的主機

port = scan_row[1] # 接收用戶輸入的端口

try:
nm = nmap.PortScanner() # 創建端口掃描對象
except nmap.PortScannerError:
print(‘Nmap not found‘, sys.exc_info()[0])
sys.exit(0)
except:
print("Unexpected error:", sys.exc_info()[0])
sys.exit(0)

try:
#scan指定掃描的命令
nm.scan(hosts=hosts, arguments=‘ -v -sS -p ‘ + port) # 調用掃描方法,參數指定掃描主機hosts,nmap掃描命令行參數arguments

except Exception as e:
print("Scan erro:" + str(e))

#all_hosts返回nmap掃描到的主機清單
for host in nm.all_hosts(): # 遍歷掃描主機
print(‘----------------------------------------------------‘)
print(‘Host : %s (%s)‘ % (host, nm[host].hostname())) # 輸出主機及主機名
print(‘State : %s‘ % nm[host].state()) # 輸出主機狀態,如up、down

for proto in nm[host].all_protocols():  # 遍歷掃描協議,如tcp、udp
    print(‘----------‘)
    print(‘Protocol : %s‘ % proto)  # 輸出協議名

    lport = nm[host][proto].keys()  # 獲取協議的所有掃描端口
    for port in lport:  # 遍歷端口及輸出端口與狀態
        print(‘port : %s\tstate : %s‘ % (port, nm[host][proto][port][‘state‘]))

端口掃描nmap