一则实用的python通过snmp抓取数据后进行分析的案例(非插件)

335 阅读2分钟

本案例通过Python3.9.7来实现

我没有使用任何netsnmp等插件,因为这个非常依赖于作者是否维护。

  1. 创建模块用于后续被调用,带有查询、查询Port-Channel对应的oid code,以及检测ping的特性
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author: Christian Tian
"""

# import sys
import os
import subprocess  # For executing a shell command


class Snmp(object):
    """A basic SNMP session"""
    def __init__(self, DestHost, Community, oid="sysDescr.0", Version='2c', Grep='""'):
        self.oid = oid
        self.version = Version
        self.destHost = DestHost
        self.community = Community
        self.grep = Grep

    def query(self):
        """Creates SNMP query session"""
        try:
            command = 'snmpget -v ' + self.version + ' -c ' +\
                     self.community + ' ' + self.destHost + ' ' + self.oid
            result = os.popen(command).readline().strip()
        except Exception as err:
            print(err)
            result = None
        return result

    def query_int_code(self):
        """Creates SNMP query session"""
        try:
            command = 'snmpwalk -v ' + self.version + ' -c ' +\
                     self.community + ' ' + self.destHost + ' ' + '.1.3.6.1.2.1.2.2.1.2' +\
                     ' | grep -w ' + self.grep
            result = os.popen(command).readline().split('.')[1].split()[0].strip()
        except Exception as err:
            print(err)
            result = None
        return result


class Ping(object):
    """Check PING result"""
    def __init__(self, DestHost):
        self.destHost = DestHost

    def ping(self):
        """Returns True if host (str) responds to a ping request."""

        command = ['ping', '-c', '1', '-W250', self.destHost]

        return subprocess.call(command, stdout=subprocess.DEVNULL) == 0
  1. 实际调用
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@author: Christian Tian
"""

from get_switch_snmp import Snmp, Ping
import datetime
import json
import os
from import_dict_into_DB import DataToMysql

session_l = []
session_d = {}
last_list = ""

# 24F_Switch2, ISP SW, DMZ SW, 6F Huawei SW 不看Uplink
# Core SW Uplink is Sangfor while Server SW Uplink is Core SW
sw_ips = ['10.21.244.1', '10.21.244.2', '10.22.22.22', '10.21.244.3', '10.21.244.4', ]
community = 'xxx'

for sw_ip in sw_ips:
    # Get IP Address
    print('\nIP: ' + sw_ip)
    session_d['ip'] = sw_ip

    # Get Device Status
    p = Ping(sw_ip)
    ping_res = p.ping()
    # if ping_res == True:
    if ping_res:
        print('Device Status: UP')
        session_d['status'] = 'UP'
    else:
        print('Device Status: DOWN')
        session_d['status'] = 'DOWN'
        continue

    # Get anything by snmp
    s = Snmp(sw_ip, community)

    # Get IOS Version
    IOSver = s.query().split(',')[-2].split()[1]
    print('IOS Ver: ' + IOSver)
    session_d['IOSver'] = IOSver

    # Get Serial Number
    s.oid = ".1.3.6.1.4.1.9.3.6.3.0"  # serial numbers chassisId
    # serial = s.query()
    # print(serial)
    serial = s.query().split('"')[1]
    print('Serial Number: ' + serial)
    session_d['serial'] = serial

    # Get Uptime
    s.oid = ".1.3.6.1.6.3.10.2.1.3.0"  # Uptime 64bit
    # serial = s.query()
    # print(serial)
    uptime = s.query().split()[3]
    # print('Uptime: ' + uptime)
    formated_uptime = datetime.timedelta(seconds=int(uptime))
    print('Uptime: ' + str(formated_uptime))
    session_d['uptime'] = str(formated_uptime)

    # Get Product Model
    s.oid = "1.3.6.1.2.1.47.1.1.1.1.13.1"
    # s.oid = ".1.3.6.1.4.1.9.3.6.3"
    # product_model = s.query()
    # print(product_model)
    product_model = s.query().split('"')[1]
    print('Product Model: ' + product_model)
    session_d['product_model'] = product_model
    
    # Get Hostname
    s.oid = ".1.3.6.1.4.1.9.2.1.3.0"  # hostname hostName
    # hostname = s.query()
    # print(hostname)
    hostname = s.query().split('"')[1]
    print('Hostname: ' + hostname)
    session_d['hostname'] = hostname

    # Get Memory Utilization
    s.oid = ".1.3.6.1.4.1.9.9.48.1.1.1.5.1"  # Used Memory
    used_mem = int(s.query().split()[3])
    # print(used_mem)
    s.oid = ".1.3.6.1.4.1.9.9.48.1.1.1.6.1"  # Free Memory
    free_mem = int(s.query().split()[3])
    # print(free_mem)
    mem = format(used_mem/(used_mem + free_mem)*100, '.2f')
    print('Memory Utilization: ' + str(mem) + '%')
    session_d['mem'] = mem + '%'

    # Get CPU Utilization
    s.oid = ".1.3.6.1.4.1.9.9.109.1.1.1.1.8.19"  # CPU#19 Utilization 5min Rev
    # cpu = s.query()
    # print(cpu)
    cpu = s.query().split()[3]
    print('CPU Utilization: ' + cpu + '%')
    session_d['cpu'] = cpu + '%'

    # Get Uplink Network Traffic
    uplink_in_old = ""
    uplink_out_old = ""
    if sw_ip == '10.21.244.1' or sw_ip == '10.21.244.2':
        s.grep = 'Port-channel10'
    elif sw_ip == '172.16.1.10':
        s.grep = 'Port-channel120'
    else:
        s.grep = 'Port-channel1'
    po_code = s.query_int_code()  # get ifDescr int Code
    print(sw_ip + ' ' + po_code + ' ' + s.grep)
    s.oid = ".1.3.6.1.2.1.31.1.1.1.6." + po_code  # Uplink Inbound Traffic
    uplink_in = s.query().split()[3]
    print('Uplink Traffic In: ' + uplink_in)

    s.oid = ".1.3.6.1.2.1.31.1.1.1.10." + po_code  # Uplink Outbound Traffic
    uplink_out = s.query().split()[3]
    print('Uplink Traffic Out: ' + uplink_out)

    session_d['uplink_in'] = uplink_in
    session_d['uplink_out'] = uplink_out

    if os.path.exists('static/switchinfo/last_list.json'):
        with open('static/switchinfo/last_list.json', 'r') as f:
            last_list = json.load(f)
        # print(last_list)

        for di in last_list:
            if di['ip'] == sw_ip:
                uplink_in_old = di['uplink_in']
                uplink_out_old = di['uplink_out']
        print('Uplink Traffic In Old: ' + uplink_in_old)
        print('Uplink Traffic Out Old: ' + uplink_out_old)

        # calculate uplink with unit Mbps (the script must be run each every 5 min)
        uplink_inbound = (int(uplink_in) - int(uplink_in_old))*8/1024/1024/300
        uplink_outbound = (int(uplink_out) - int(uplink_out_old))*8/1024/1024/300
        print('Uplink Traffic Inbound(Mbps): ' + str(int(uplink_inbound)) + ' Mbps')
        print('Uplink Traffic Outbound(Mbps): ' + str(int(uplink_outbound)) + ' Mbps')
        session_d['uplink_inbound'] = str(int(uplink_inbound)) + ' Mbps'
        session_d['uplink_outbound'] = str(int(uplink_outbound)) + ' Mbps'

    # Append Dict into List & Clear Dict
    session_l.append(session_d)
    session_d = {}
    session_d.clear()

print(session_l)

# Output as JSON for next loop of calculating uplink traffic
jsObj = json.dumps(session_l)  
  
fileObject = open('static/switchinfo/last_list.json', 'w')
fileObject.write(jsObj)  
fileObject.close() 


# Import into MySQL DB
mysql = DataToMysql('localhost', 'root', 'Pxxxwd', 'the_test')

# mysql.remove_db('test')
dicts = session_l
for di in dicts:
    mysql.write('switchinfo', di)