예제 #1
0
def monitor_router(router):
    ip_address = str(router[0])
    community = str(router[1])
    hostname = str(router[2])
    status = {}
    warning = []
    status.update({"Type": "Router"})
    status.update({"Host": hostname})
    status.update({"IP": ip_address}) 
    cpu = quicksnmp.get(ip_address, [OID_CISCO_CPU_LOAD], hlapi.CommunityData(community))
    ram = quicksnmp.get(ip_address, [OID_CISCO_MEMORY], hlapi.CommunityData(community))
    ramm = 90
    ramm = round(memory_percent_router(float(ram), 512.00),2)
    status.update({"CPU%": float(cpu)})
    status.update({"Memory%": round(memory_percent_router(float(ram), 512.00),2)})
    if hostname == "Akagi":
        i = quicksnmp.get(ip_address, [OID_AKAGI_IN], hlapi.CommunityData(community))
        o = quicksnmp.get(ip_address, [OID_AKAGI_OUT], hlapi.CommunityData(community))
        s = quicksnmp.get(ip_address, [OID_AKAGI_SPEED], hlapi.CommunityData(community))
        bandwidth = calculate_bandwidth(i,o,s,300)
        status.update({"Bandwidth": bandwidth})
    elif hostname == "Shoukaku":
        i = quicksnmp.get(ip_address, [OID_SHOUKAKU_IN], hlapi.CommunityData(community))
        o = quicksnmp.get(ip_address, [OID_SHOUKAKU_OUT], hlapi.CommunityData(community))
        s = quicksnmp.get(ip_address, [OID_SHOUKAKU_SPEED], hlapi.CommunityData(community))
        bandwidth = calculate_bandwidth(i,o,s,300)
        status.update({"Bandwidth": bandwidth})
    if float(cpu) >= 70.0 or ramm >= 80:
        warning.append("ip: "+ ip_address)
        warning.append("host: "+ hostname)
        warning.append("cpu: " + str(cpu))
        warning.append("memory: " + str(ram))
    return status, warning
예제 #2
0
def monitor_pc(pc):
    ip_address = str(pc[0])
    community = str(pc[1])
    hostname = str(pc[2])
    status = {}
    warning = []
    status.update({"Type": "PC"})
    status.update({"Host": hostname})
    status.update({"IP": ip_address})
    cpu = quicksnmp.get(ip_address, [OID_PC_LOAD], hlapi.CommunityData(community))
    used_ram = quicksnmp.get(ip_address, [OID_PC_USED_RAM], hlapi.CommunityData(community))
    total_ram = quicksnmp.get(ip_address, [OID_PC_TOTAL_RAM], hlapi.CommunityData(community))
    status.update({"CPU%": float(cpu)})
    ram = 80.0
    ram = round(memory_percent_pc(float(used_ram), float(total_ram)),2)
    status.update({"Memory%": round(memory_percent_pc(float(used_ram), float(total_ram)),2)})
    hdd = quicksnmp.get(ip_address, [OID_PC_USED_DISK], hlapi.CommunityData(community))
    status.update({"HDD%": int(hdd)})
    i = quicksnmp.get(ip_address, [OID_PC_IN], hlapi.CommunityData(community))
    o = quicksnmp.get(ip_address, [OID_PC_OUT], hlapi.CommunityData(community))
    s = quicksnmp.get(ip_address, [OID_PC_SPEED], hlapi.CommunityData(community))
    bandwidth = calculate_bandwidth(i,o,s,300)
    status.update({"Bandwidth": bandwidth})
    if float(cpu) >= 70.0 or ram >= 80 or int(hdd) >= 90:
        warning.append("ip: "+ ip_address)
        warning.append("host: "+ hostname)
        warning.append("cpu: " + str(cpu))
        warning.append("memory: " + str(ram))
        warning.append("hdd%: "+ str(hdd))
    return status, warning
예제 #3
0
def get_hostname(ip):
    """
    inputs:
        ip (str) : Device IP address
    
    outputs:
        Tuple : (Chassis ID, [Device information])
    """
    global devices

    def create_dict(*args):
        return dict({i: eval(i) for i in args})

    try:
        with no_stdout():
            vendor = quicksnmp.get(str(ip), snmp_ping, credentials)
    except:
        return False
    else:
        address = str(ip)
        vendor = str(vendor[0][1])
        id = ''
        if vendor == "Optix product":
            vendor = "huawei"
            ne_id = str(
                quicksnmp.get_oid(str(ip), hua_ne_id, credentials)[0][-1])
            hostname = str(
                quicksnmp.get_oid(str(ip), huawei_sysname, credentials)[0][1])
            id = '0x' + str(
                quicksnmp.get(str(ip), lldp_hua_id,
                              credentials)[0][1]).replace('-', '')
            return (id, [address, hostname, vendor, ne_id])
        elif vendor == 'ipe':
            vendor = "nec-ipa"
            hostname = str(
                quicksnmp.get(str(ip), sysName_named_oid, credentials)[0][1])
            id = quicksnmp.get(str(ip), lldp_id,
                               credentials)[0][1].prettyPrint()
        elif vendor == '-':
            try:
                #Checking the "Equipment Type" OID that return an integer >10000 for VR products
                if int(
                        str(
                            quicksnmp.get_oid(address, nec_vr_type,
                                              credentials)[0][1])) > 10000:
                    vendor = "nec-vr"
                    hostname = str(
                        quicksnmp.get(str(ip), sysName_named_oid,
                                      credentials)[0][1])
                    id = quicksnmp.get(str(ip), lldp_id,
                                       credentials)[0][1].prettyPrint()
                else:
                    raise ValueError('')
            except:
                return False
        if id == '': return False
        return (id, [address, hostname, vendor])
예제 #4
0
def main_with_args(args):
    log("############")
    log("# Starting #")
    log("############")
    '''
    Lets create a data model of the topology from the above information
    '''
    topology_model = NetworkTopology()

    '''
    Lets go via devices and get data
    '''
    config = configparser.ConfigParser()
    config.read('config.ini')
    config.sections()
    if 'DEVICES' not in config or 'DEFAULT' not in config:
        log('We failed to load the configuration file, and sections from it, exiting')
        exit(1)

    for device in json.loads(config['DEVICES']['devices']):
        device = device.replace('\n', '')
        print("")
        print("############################################")
        print(f'Testing access to {device:15} ...', end=" ")
        log("Testing access to " + device)

        '''
        Try getting first the device hostname to check if SNMP works
        '''
        try:
            sSNMPHostname = quicksnmp.get(device, sysName_named_oid,
                                          hlapi.CommunityData(config['DEFAULT']['SnmpCommunityString']))
            log(' = '.join([x.prettyPrint() for x in sSNMPHostname]))
            log(" This is how to get to numeric OID: " + str(tuple(sSNMPHostname[0][0])))
            log(" This is how to get data only: " + str(sSNMPHostname[0][1]))
        except RuntimeError as e:
            log("Runtime Error: " + str(e))
            continue
        except (ValueError, TypeError):
            log("Error " + str(TypeError))
            continue

        log("# Connection worked, will retrieve data next")

        '''
        INTERFACES TABLE GET
        '''
        try:
            log("INTERFACES TABLE: ")
            rawInterfacesTable = quicksnmp.get_table(device, interfaces_table_named_oid,
                                                     hlapi.CommunityData(config['DEFAULT']['SnmpCommunityString']))
            for row in rawInterfacesTable:
                for item in row:
                    log(' = '.join([x.prettyPrint() for x in item]))
                log('')

        except RuntimeError as e:
            log("Runtime Error: " + str(e))
            continue
        except (ValueError, TypeError):
            log("Error " + str(TypeError))
            continue

        '''
        LLDP TABLE GET
        '''
        try:
            log("LLDP TABLE: ")
            log("############")
            rawTable = quicksnmp.get_table(device, lldp_table_named_oid,
                                           hlapi.CommunityData(config['DEFAULT']['SnmpCommunityString']))
            for row in rawTable:
                for item in row:
                    log(' = '.join([x.prettyPrint() for x in item]))
                log('')

        except RuntimeError as e:
            log("Runtime Error: " + str(e))
            continue
        except (ValueError, TypeError):
            log("Error " + str(TypeError))
            continue

        ''' 
        Populate data model with this device data
        '''
        topology_model.addDevice(str(sSNMPHostname[0][1]))

        for row in rawInterfacesTable:
            # index number from OID
            oid = tuple(row[0][0])
            log('INDEX: ' + str(oid[-1]))
            # ifDescr
            log('ifDescr: ' + str(row[0][1]))
            # ifType
            log('ifType: ' + str(row[1][1]))
            # ifMtu
            log('ifMtu: ' + str(row[2][1]))
            # ifSpeed
            log('ifSpeed: ' + str(row[3][1]))
            # ifPhysAddress
            log('ifPhysAddress: ' + str(row[4][1].prettyPrint()))
            # ifAdminStatus
            log('ifAdminStatus: ' + str(row[5][1]))
            # ifOperStatus
            log('ifOperStatus: ' + str(row[6][1]))
            # ifHCInOctets
            log('ifHCInOctets: ' + str(row[7][1]))
            # ifHCOutOctets
            log('ifHCOutOctets: ' + str(row[8][1]))
            # ifHighSpeed
            log('ifHighSpeed: ' + str(row[9][1]))
            log("")

            topology_model.addDeviceInterface(str(sSNMPHostname[0][1]),  # deviceid
                                              oid[-1],  # INDEX
                                              str(row[0][1]),  # ifDescr
                                              str(row[1][1]),  # ifType
                                              str(row[2][1]),  # ifMtu
                                              str(row[3][1]),  # ifSpeed
                                              str(row[4][1].prettyPrint()),  # ifPhysAddress
                                              str(row[5][1]),  # ifAdminStats
                                              str(row[6][1]))  # ifOperStatus

            topology_model.addInterfaceStats(str(sSNMPHostname[0][1]),  # deviceid
                                             oid[-1],  # INDEX
                                             str(row[0][1]),  # ifDescr
                                             str(row[1][1]),  # ifType
                                             str(row[6][1]),  # ifOperStatus
                                             str(row[7][1]),  # ifHCInOctets
                                             str(row[8][1]),  # ifHCOutOctets
                                             str(row[9][1]))  # ifHighSpeed

        log('links from LLDP')
        for row in rawTable:
            # lldpRemSysName
            log('lldpRemSysName: ' + str(row[0][1]))
            # lldpRemSysDesc
            log('lldpRemSysDesc: ' + str(row[1][1]))
            # lldpRemPortId
            log('lldpRemPortId: ' + str(row[2][1]))
            # lldpRemPortDesc
            log('lldpRemPortDesc: ' + str(row[3][1]))

            # Add to neighborships
            oid = tuple(row[0][0])
            local_in_index = oid[-2]
            # Get interface name via LLDP local int table
            local_interface_name = quicksnmp.get(device, [('LLDP-MIB', 'lldpLocPortId', local_in_index)],
                                                 hlapi.CommunityData(config['DEFAULT']['SnmpCommunityString']))

            # Repairing H3Cs bad indexes by searching for index via name
            local_in_index = topology_model.getDeviceInterfaceIndex(str(sSNMPHostname[0][1]), str(local_interface_name[0][1]))

            log("Local_interface_name: " + str(local_interface_name[0][1]))
            log(' = '.join([x.prettyPrint() for x in local_interface_name]))

            # Add to links
            topology_model.addLink(str(sSNMPHostname[0][1]),  # node_a
                                   str(row[0][1]),  # node_b
                                   topology_model.getLinkSpeedFromName(str(row[2][1])),
                                   local_in_index,  # a_local_int_index
                                   str(local_interface_name[0][1]),  # a_local_int_name
                                   str(row[2][1])  # lldpRemPortId
                                   )

            log("Localintindex : " + str(local_in_index))
            topology_model.addNeighborships(str(sSNMPHostname[0][1]),
                                            local_in_index,
                                            str(local_interface_name[0][1]),
                                            str(row[0][1]),
                                            str(row[2][1]))

    '''
    The model should be populated now, lets dump the JSONs
    '''
    topology_model.dumpToJSON()
    del topology_model

    return 0;
예제 #5
0
from pysnmp import hlapi
import quicksnmp
from getpass import getpass

print('Welcome to quick SNMP access.  Enter Agent Info below.\n')
hostip = input('Host IP Address: ')
community = getpass('Community name: ')

# Using SNMPv2c, we set the hostname of the remote device to 'SNMPHost'
# NOTE: if your community name is set for rocommunity, then this next line 'set' will throw an exception
#quicksnmp.set(hostip, {'1.3.6.1.2.1.1.5.0': 'mySNMPAgent'}, hlapi.CommunityData(community))

# Using SNMPv2c, we retrieve the hostname of the remote device
print(
    quicksnmp.get(hostip, ['1.3.6.1.2.1.1.5.0'],
                  hlapi.CommunityData(community)))

# We get interface name and Cisco interface description for all interfaces
# The last parameter is the OID containing the number of interfaces, so we can loop 'em all!
its = quicksnmp.get_bulk_auto(
    hostip, ['1.3.6.1.2.1.2.2.1.2 ', '1.3.6.1.2.1.31.1.1.1.18'],
    hlapi.CommunityData(community), '1.3.6.1.2.1.2.1.0')
# We print the results in format OID=value
for it in its:
    for k, v in it.items():
        print("{0}={1}".format(k, v))
    # We leave a blank line between the output of each interface
    print('')
예제 #6
0
def main(argv):
    pingip = ''  # IP we want to ping
    checkip = ''  # ePMP IP the snmp command checks
    snmpCommunity = 'public'  # default SNMP community
    snmpIndex = ''  # Index for the LAN port

    try:
        opts, args = getopt.getopt(argv, "hp:c:",
                                   ['co='])  # Get the command line arguments
    except getopt.GetoptError:
        '''
        Error handling from getting option, usually none are set
        '''
        print('snmpcheck.py -p pingip -c checkip --co=SNMPCommunity')
        sys.exit(2)

    # print(opts)
    for opt, arg in opts:
        if opt == '-h':  # Help print request
            print('snmpcheck.py -p pingip -c checkip --co=SNMPCommunity')
            print('Default SNMP community is RNET41699')
            sys.exit(0)
        elif opt == '-p':
            pingip = arg  # The IP we need to ping
        elif opt == '-c':
            checkip = arg  # The IP we need to SNMP against
        elif opt == '--co':
            snmpCommunity = arg  # The SNMP community

    x = True  # Main loop control
    y = True  # Flag if the pings have dropped
    pcount = 0  # Bad ping counter
    while x:
        z = ping(pingip)  # ping the IP and save if it returned
        if not z:  # if it didn't
            print('Dropped a packet')
            pcount += 1  # count the drop
            y = z  # record that it dropped
            if snmpIndex == '':  # If this is the first drop and we don't have the index of the LAN interface
                links = quicksnmp.get_bulk_auto(
                    checkip, ['1.3.6.1.2.1.2.2.1.2', '1.3.6.1.2.1.2.2.1.8'],
                    hlapi.CommunityData(snmpCommunity),
                    '1.3.6.1.2.1.2.1.0')  # Walk the radio interface table
                # print(links)
                for link in links:  # Iterate results (should be a list of tupples)
                    for k, v in link.items():  # iterate the tupples
                        if isinstance(
                                v, str
                        ) and v[:3] == 'LAN':  # If the description starts with LAN (ePMP have WLAN and LAN)
                            oids = k.split(
                                '.')  # Split the OID listing to get the index
                            snmpIndex = list.pop(
                                oids)  # save the index for future runs
                            break  # Jump out of the loop
                    if snmpIndex != '':  # If we found the index
                        updown = link['1.3.6.1.2.1.2.2.1.8.{}'.format(
                            snmpIndex)]  # Get the current link state
                        break  # Stop running through the loop of links
            else:  # If we already know the index of the interface
                updown = quicksnmp.get(
                    checkip, ['1.3.6.1.2.1.2.2.1.8.{}'.format(snmpIndex)],
                    hlapi.CommunityData(snmpCommunity))[
                        '1.3.6.1.2.1.2.2.1.8.{}'.format(
                            snmpIndex)]  # Get the link state

            with open(
                    'snmplog.txt', 'a'
            ) as f:  # open the log file for writing and print/log the output
                if updown == 1:
                    print('Link is Up')
                    f.write('{} - Link is UP\n'.format(datetime.now()))
                elif updown == 2:
                    print('Link is down')
                    f.write('{} - Link is DOWN\n'.format(datetime.now()))
                else:  # Catch all for various optional states in the MIB
                    print('Link unknown')
                    f.write('{} - Link is UNKNOWN\n'.format(datetime.now()))
        elif not y:  # If we pinged, but the last one failed
            if pcount > 9:  # if it failed more than 9 times, break the loop to stop the program
                x = False
            else:  # otherwise restart the counter and keep going
                pcount = 0
                y = True
            print('Ping is back')
예제 #7
0
           ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))))

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' %
          (errorStatus.prettyPrint(),
           errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
    for varBind in varBinds:
        print(' = '.join([x.prettyPrint() for x in varBind]))
print("\n\n")
print(varBinds)
print('')
#uptime
uptime = quicksnmp.get('demo.snmplabs.com', ['.1.3.6.1.2.1.1.3.0'],
                       hlapi.CommunityData('public', mpModel=0))
for k, v in uptime.items():
    print(("Up Time: {} days").format(v / 60 / 60 / 24))
# We leave a blank line between the output of each interface
print('')
#quicksnmp.set('demo.snmplabs.com', {'.1.3.6.1.2.1.1.1.0': 'Test'}, hlapi.CommunityData('public', mpModel=0))

location = quicksnmp.get('demo.snmplabs.com', ['.1.3.6.1.2.1.1.6.0'],
                         hlapi.CommunityData('public', mpModel=0))
for k, v in location.items():
    print(("Location: {}").format(v))
# We leave a blank line between the output of each interface
print('')
'''
its = quicksnmp.get_bulk_auto('demo.snmplabs.com', ['1.3.6.1.2.1.2.2.1.2', '1.3.6.1.2.1.31.1.1.1.18'], hlapi.CommunityData('public', mpModel=0), '1.3.6.1.2.1.2.1.0')
for it in its:
예제 #8
0
def getn(oid):
    global host
    return get(host, [oid], hlapi.CommunityData(community)).get(oid)