Python-Nmap

案例前提条件:

python基础 pip

TCP/IP协议群

python 3.7.x

python-nmap

  • postscanner()
  • postscannerhostdict()

内网端口扫描工具

#coding=utf-8
# 准备工作:
# windows nmap.exe ->32/64
# linux yum -y install nmap
# python-nmap pip install python-nmap
# 目标  实现指令IP/IP范围的端口扫描神器

import nmap
import sys

# nm = nmap.PortScanner()
# nm.scan('192.168.1.11', '22,80,443')  #靶机IP,端口范围
# nm.command_line()
# nm.scaninfo()
# nm['192.168.1.11'].hostname()

# www.baidu.com/127.0.0.1/192.168.0-255.1-255/192.168.1.1/24
# 1-8080/80/1443,8080,443
# scan(self,hosts='127.0.0.1',ports=None,arguments='-sV')

scan_row = []
input_data = input("please input host and ports:")  # 192.168.0.1 80,443
scan_row = input_data.split(" ")
# 输入的内容是否满足条件
if len(scan_row) != 2:
    print("Input error.Example \"192.168.0.1 80,443\"")
    sys.exit(0)

hosts = scan_row[0]  # 主机
port = scan_row[1]  # 端口

# 创建一个扫描对象
try:
    nm = nmap.PortScanner()
except Exception as e:
    print("Nmap not found")
    sys.exit(0)

# 遍历扫描的主机
nm.scan(hosts=hosts, arguments=' -v -sS -p ' + port)
for host in nm.all_hosts():
    print('-' * 40)
    print('Host:{}({})'.format(host, nm[host].hostname()))
    print('State:{}'.format(nm[host].state()))  # 输出主机状态,up/down

    for proto in nm[host].all_protocols():  # 遍历扫描所有的协议,tcp/udp
        print("-" * 20)
        print("protocol:{}".format(proto))

        # 扫描所有端口所对应的状态
        lport = nm[host][proto].keys()
        for port in lport:
            print("port:{}\tstate:{}".format(port, nm[host][proto][port]['state']))