用来扫描一些网段的ip和端口的存活

本文介绍了一个使用Python和Nmap进行IP及端口存活状态扫描的脚本。该脚本可以针对特定的IP地址范围和端口进行扫描,并输出存活的IP地址及其状态。通过对指定网段内的主机进行扫描,能够帮助了解网络中设备的分布情况。
摘要由CSDN通过智能技术生成

用来扫描一些网段的ip和端口的存活

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'xiaojinsong'
# __time__ = '2018/2/28'

import sys
from nmap import PortScanner
from nmap import PortScannerError


class NmapScan():
    def __init__(self, scan_hosts, scan_port):
        self.scan_Hosts = scan_hosts
        self.scan_Port = scan_port
        self.survivedict = {}
        self.deaddict = {}

    def program_scan(self):
        try:
            nm = PortScanner()
        except PortScannerError:
            print('Nmap not found,', sys.exc_info()[0])
            sys.exit(0)
        except:
            print("Unexcept error:", sys.exc_info()[0])
            sys.exit(0)

        for scan_host in self.scan_Hosts:
            try:
                nm.scan(scan_host, arguments='-v -sS -p' + self.scan_Port)
            except Exception as e:
                print("Scan Error: " + str(e))

            survive = []
            deadip = []
            for host in nm.all_hosts():
                if nm[host].state() == 'up':
                    print('-----------------------------------------------------')
                    print('Host : %s (%s)' % (host, nm[host].hostname()))
                    print('State : %s' % nm[host].state())
                    survive.append(host)
                elif nm[host].state() == 'down':
                    deadip.append(host)

                for proto in nm[host].all_protocols():
                    print('----------------------------')
                    print('Protocol : %s ' % proto )

                    lport = nm[host][proto].keys()
                    lport = sorted(lport)

                    for port in lport:
                        print('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))

            self.deaddict[scan_host] = deadip
            self.survivedict[scan_host] = survive

if __name__ == '__main__':
    scan_hosts = ['10.200.18.0/24', '10.200.13.0/24', '10.200.19.0/24', '10.200.15.0/24']
    scan_port = '21,22,23,80,8080,1521,3306'
    nmapS = NmapScan(scan_hosts, scan_port)
    nmapS.program_scan()
    for key,value in nmapS.survivedict.items():
        print(key, value)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值