每天都学一点

python通过nmap扫描在线设备并尝试AAA登录

13 04月
作者:林健|分类:Python

如果管理网络设备很多,不可能靠人力每天去登录设备去查看是否在线。所以,可以利用python脚本通过每天扫描网络中的在线设备。可以部署在服务器上做成定时任务,每天发送AAA巡检报告。

下面是我写的一个python练手小程序。用来扫描一个网段中的在线主机,并尝试AAA去登录。统计一个大网段内可以成功aaa登录的主机。

注意:

该程序只是测试小程序,还有些小bug需要解决。不是通用的程序。主要提供一个大致思路。

主要用到了python-nmap, paramiko库。

程序大概思路:

  1. 利用nmap扫描一个指定网段,只做ping扫描,所以前提所管理的设备中ping必须开启。获取存活设备IP列表。

  2. 利用paramiko库模拟ssh去登录个IP,如果登录成功,返回设备名称,并及将设备名称和对应ip写入文件。

代码示例:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
# -*- coding: utf-8 -*-import nmap import datetimeimport paramikoimport redef get_name(host,  user, password, port=22):    client = paramiko.SSHClient()    client.load_system_host_keys()    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #client.connect(host, port, user, password, allow_agent=False, look_for_keys=False, timeout=5)    try:        client.connect(ip, port, user, password, allow_agent=False, look_for_keys=False, timeout=3)    except Exception as err:        return 0, str(err)    #get shell    ssh_shell = client.invoke_shell()    dev_name = ''    while True:        line = ssh_shell.recv(1024)        if line.endswith(b'>'):#华为 华三            dev_name = re.findall(r'<(.*)>', str(line))[0]            #dev_name = str(line)[3:-2]            break        if line.endswith(b'# ') | line.endswith(b'#'): #思科            dev_name = re.findall(r'[\\r\\n|\\r]+(.*)#', str(line))[0]            break        if line.endswith(b'> '):             if 'ConnetOS' in str(line):#分流器                dev_name =re.findall(r'[\\r\\n|\\r]+(.*)>', str(line))[0].strip()            if '@' in str(line): #junpier防火墙                dev_name =re.findall(r'@(.*)>', str(line))[0].strip()            break    #怎么跳出recv阻塞    ssh_shell.close()    return 1, dev_name#print('扫描时间:'+res['nmap']['scanstats']['timestr']+'\n命令参数:'+res['nmap']['command_line']) def get_ip_list(hosts):    nm = nmap.PortScanner()    #nmap填入参数列表可以填很多    res = nm.scan(hosts=hosts, arguments='-sn -PE')    #count = res['nmap']['scanstats']['uphosts'] #存活的主机数    return list(res['scan'].keys()) #存活主机IP地址        if __name__ == '__main__':    start = datetime.datetime.now()    user = 'user'    password = 'password'    hosts = '10.0.0.0/24'    dev = {} #存放AAA登录成功的主机    f = open('ip_list.txt', 'w') #存放能ping通的IP    ip_list = get_ip_list(hosts)     end = datetime.datetime.now()    #f.write("存活的IP地址有:" +  str(len(ip_list)) + "\n")    #f.write("程序运行时间:" + str(end-start) + '\n')    for ip in ip_list:        f.write(ip + '\n')    f.close()    #print(ip_list)    login_failed_count = 0    f1 = open('login_succeed.txt', 'w', encoding='utf-8')    f2 = open('login_failed.txt', 'w', encoding='utf-8')    f3 = open('mtil_add.txt', 'w', encoding='utf-8')    #ip_list = ip_list.split('\n')    for ip in ip_list:        ok, dev_name = get_name(ip, user, password)        if ok == 1:            if dev_name not in dev.keys():                vendor = ''                 print(dev_name + "\t\t" + ip)                if 'h' in dev_name[-12:]:                    vendor = 'h3c'                elif 'c' in dev_name[-12:]:                    vendor = 'cisco'                elif 'w' in dev_name[-12:]:                    vendor = 'huawei'                else:                    vendor = 'unknow'                f1.write(dev_name + '\t\t' +  ip + '\t' + vendor + '\n')                f1.flush()                dev.update({dev_name : ip})            else:                f3.write(dev_name + '\t\t' + str(dev[dev_name]) + '  ' + ip +'\n')                print(dev_name + '\t\t' + str(dev[dev_name]) + '  ' + ip +'\n')                dev.update({dev_name: [dev[dev_name] , ip]})                f3.flush()        else:            login_failed_count += 1            print(dev_name)            f2.write(dev_name + '\t\t' + ip  + '\n')            f2.flush()    end = datetime.datetime.now()    f1.write('AAA登录成功' + str(len(dev)) +'台\n' )    f1.write('AAA登录失败' + str(login_failed_count) +'台\n' )    f1.write("程序运行时间:" + str(end-start) +'\n')    f1.close()    f2.close()    f3.close()        print("程序运行时间:" + str(end-start) +'\n')    print("存活的IP地址有:" +  str(len(ip_list)) + "\n")    print("AAA登录成功:" + str(len(dev)) + "\n")    print('AAA登录失败' + str(login_failed_count) +'台\n')

这个小程序例子,只是一个大概思路。

可以添加或则改善的思路:

  • 比想要获取设备名,可以通过snmp,知道ip地址和snmp读团体名就可以直接获取。

  • 可以将获取到的数据存入数据库中,从而可以做更的事情。

  • 通过类似代码,也可以实现每天去设备上备份网络配置等功能。

  • 可以将利用扫描结果,添加更多处理逻辑,生成每日巡检日报,通过邮件或者短信发送。

nmap库使用:

nmap工具使用可参考: nmap扫描工具学习笔记)

如果在windows上写nmap库,有两个事要解决。

第一步:安装nmap软件

因为在python程序中,nmap包所调用的是nmap可执行程序,所以必须先安装nmap软件。nmap下载地址: https://nmap.org/download.html

第二步: 需要在nmap库中文件的init方法中添加的nmap.exe的路径。

不然会报错,提示找不到nmap。

在nmap.py的class PortScanner()中的__init__()中更改:

1
def __init__(self, nmap_search_path=('nmap', '/usr/bin/nmap', '/usr/local/bin/nmap', '/sw/bin/nmap', '/opt/local/bin/nmap',r"D:\software\nmap-7.80\nmap.exe")):

主要添加了‘r”D:\software\nmap-7.80\nmap.exe”, nmap.exe可执行文件路径。


1234
import nmapnm = nmap.PortScanner()#nmap填入参数列表可以填很多res = nm.scan(hosts=hosts, arguments='-sn -PE')

其他使用示例:

12345678910111213141516171819202122
#!/usr/bin/env pythonimport nmap # import nmap.py modulenm = nmap.PortScanner() # instantiate nmap.PortScanner objectnm.scan('127.0.0.1', '22-443') # scan host 127.0.0.1, ports from 22 to 443nm.command_line() # get command line used for the scan : nmap -oX - -p 22-443 127.0.0.1nm.scaninfo() # get nmap scan informations {'tcp': {'services': '22-443', 'method': 'connect'}}nm.all_hosts() # get all hosts that were scannednm['127.0.0.1'].hostname() # get one hostname for host 127.0.0.1, usualy the user recordnm['127.0.0.1'].hostnames() # get list of hostnames for host 127.0.0.1 as a list of dict# [{'name':'hostname1', 'type':'PTR'}, {'name':'hostname2', 'type':'user'}]nm['127.0.0.1'].hostname() # get hostname for host 127.0.0.1nm['127.0.0.1'].state() # get state of host 127.0.0.1 (up|down|unknown|skipped)nm['127.0.0.1'].all_protocols() # get all scanned protocols ['tcp', 'udp'] in (ip|tcp|udp|sctp)nm['127.0.0.1']['tcp'].keys() # get all ports for tcp protocolnm['127.0.0.1'].all_tcp() # get all ports for tcp protocol (sorted version)nm['127.0.0.1'].all_udp() # get all ports for udp protocol (sorted version)nm['127.0.0.1'].all_ip() # get all ports for ip protocol (sorted version)nm['127.0.0.1'].all_sctp() # get all ports for sctp protocol (sorted version)nm['127.0.0.1'].has_tcp(22) # is there any information for port 22/tcp on host 127.0.0.1nm['127.0.0.1']['tcp'][22] # get infos about port 22 in tcp on host 127.0.0.1nm['127.0.0.1'].tcp(22) # get infos about port 22 in tcp on host 127.0.0.1nm['127.0.0.1']['tcp'][22]['state'] # get state of port 22/tcp on host 127.0.0.1 (open

参考文档:

https://pypi.org/project/python-nmap/


    浏览6 评论0
    返回
    目录
    返回
    首页
    堡垒机(运维审计系统)的基本原理与部署方式 PYQT学习

    发表评论