python实现高效的端口扫描器实战

一 点睛

本次实践通过python-nmap实现一个高效的端口扫描工具,与定时作业crontab及邮件告警结合,可以很好地帮助我们及时发现异常开放的高危端口。当然,该工具也可以作为业务服务端口的可用性探测,例如扫描192.168.0.100-125网段ClamAV服务端口3310是否处于open状态。实践所采用 的scan()方法的arguments参数指定为“-v-PE-p'+端口”,-v表示启用细 节模式,可以返回非up状态主机清单;-PE表示采用TCP同步扫描(TCP SYN)方式;-p指定扫描端口范围。

代码输出部分采用了三个for循环体,第一层遍历扫描主机,第二层为遍历协议,第三层为遍历端口,最后输出主机状态。

二 代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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 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:
    nm.scan(hosts=hosts, arguments=' -v -sS -p ' + port)  # 调用扫描方法,参数指定扫描主机hosts,nmap扫描命令行参数arguments
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())  # 输出主机状态,如up、down

    for proto in nm[host].all_protocols():  # 遍历扫描协议,如tcp、udp
        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']))

三 结果

[root@localhost /]# python test1.py
Please input hosts and port: 192.168.0.120 22,80,3310
----------------------------------------------------
Host : 192.168.0.120 ()
State : up
----------
Protocol : tcp
port : 22    state : open
port : 80    state : open
port : 3310    state : open
[root@localhost /]# python test1.py
Please input hosts and port: 192.168.0.106 22,80,3310
----------------------------------------------------
Host : 192.168.0.106 ()
State : up
----------
Protocol : tcp
port : 22    state : filtered
port : 80    state : filtered
port : 3310    state : filtered

 

你可能感兴趣的:(python)