使用python-nmap来扫描端口信息
简介如何使用Python来扫描计算机的开放端口呢?Python中提供了python-nmap包,所以使用非常方便,本文主要记录如何使用python-nmap来扫描端口信息。
一、安装
python 使用python-nmap来扫描端口信息,首先要在系统中安装nmap,命令如下
yum install nmap
二、使用
使用代码如下:
# coding=utf-8
import sys
import nmap
input_raw = raw_input("Please input hosts and port:")
print "input_row: " + input_raw
rows = input_raw.split(" ")
if len(rows) != 2:
print "input row Error"
exit()
hosts = rows[0]
ports = rows[1]
try:
nm = nmap.PortScanner()
except nmap.PortScannerError:
print "Nmap not fount",sys.exc_info()[0]
exit()
except:
print "Unexpected error:", sys.exc_info()[0]
try:
nm.scan(hosts=hosts, arguments=' -v -sS -p '+ports)
except Exception, e:
print "Scan erro:" + str(e)
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\tstate: %s"%(port,nm[host][proto][port]['state'])
运行:
python test.py
输出:
10.3.15.10-20 80,22,433,3306
``