要实现端口状态扫描需要用到python的namp模块。

先到地址:https://pypi.python.org/pypi/python-nmap下载namp的软件包。

我这里下载的是0.6.1版本,OS是centos 7。

执行如下命令安装namp模块:

cd python-nmap-0.6.1

python setup install


python实现代码如下:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

#python version:  Python 2.7.5


import sys

import nmap

scan_row=[]

input_data=raw_input("please input hosts and port: ")

scan_row=input_data.split(" ")

if len(scan_row) !=2:

  print 'input error! for example:192.168.18.128 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("unexcepten error:", sys.exc_info()[0])

  sys.exit(0)


try:

  nm.scan(hosts=hosts,arguments='-v -sS -p'+port)

except Exception,e:

  print "scan error: "+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']))