Exemple #1
0
def main():
    parser = optparse.OptionParser(usage=__doc__)
    parser.add_option("-c",
                      help="snmp agent's community", default=COMMUNITY, dest="community", metavar="COMMUNITY")
    parser.add_option("-v",
                      help="snmp version: default is %default", default=SNMPVER, dest="snmpver", metavar="VERSION")
    parser.add_option("-u",
                      help="update interval: default is %default", dest="updtime", default=UPDTIME, metavar="SECONDS")
    parser.add_option("-m",
                      help="set maximum bandwidth manually", dest="maxspeed", default=None, metavar="BITS/S")
    parser.add_option("--64",
                      help="force to use 64 bit counters", action="store_true", dest="use64bit", default=False)
    parser.add_option("-g", "--hist",
                      action="store_false", dest="hist", default=True,
                      help="histogram mode")
    parser.add_option("-t",
                      action="store_true", dest="histT", default=False,
                      help="histogram mode with timestamps")
    parser.add_option("-l",
                      action="store_true", dest="list", default=False,
                      help="list index of available interfaces")
    parser.add_option("-q",
                      action="store_true", dest="verbose", default=False,
                      help="verbose output")
    (opts, args) = parser.parse_args()
    if len(args) < 1:
        parser.error("no address specified")

    opts.address = args[0]
    opts.updtime = int(opts.updtime)
    if len(args) > 1:
        opts.if_name = args[1]
    else:
        opts.if_name = None
    if opts.address is None:
        parser.error("no address specified")
    elif opts.community is None:
        parser.error("no community specified")
#######################################################################################################################

    if opts.verbose: print('* Trying the host {0}...'.format(opts.address))
    poller = SnmpIfInfo(opts.address, opts.community, opts.snmpver)
    poller.get_sysdescr()
    if opts.verbose: print poller.sysdescr
    
    rows, columns = terminal_size()
    if opts.verbose: print '* Getting interface table...'
    poller.get_ifnametable()
    
    if opts.if_name:
        try:
            poller.find_interface_id(opts.if_name)
        except MyError: pass
    if not hasattr(poller, 'if_id') or opts.verbose or opts.list:
        print 'Available interface list:'
        print '-' * columns
        print sorted(poller.ifnametable, key=poller._sort_natural)
        print '-' * columns
    if opts.list:
        from modules.mytable import formatTable
        print 'Detailed interface list:'
        iftable = poller.get_iftable()
        labels = ('ifIndex', 'ifName', 'ifAlias', 'ifDescr')
        table = []
        for i in iftable:
            table.append([i['ifid'], i['ifname'], i['ifalias'], i['ifdescr']])
        # autofit table width:
        for i in [0] + range(30, 1, -1):
            outTable = formatTable([labels] + table, separateRows=2, border='|',
                                            leftBorder='|', rightBorder='|', width=i)
            tablelen = outTable.find('\n')
            if columns-tablelen > 1:
                break
        print outTable
        sys.exit()
    if not hasattr(poller, 'if_id'):
        if opts.if_name: raise
        else: raise MyError('no interface specified')

    poller.get_sysname()
    print poller.sysname.center(columns)
    print poller.sysdescr.splitlines()[0][:columns].center(columns)
    print '-' * columns
    rs = snmpget(poller.address, OIDS['ifDescr'] + '.' + poller.if_id, poller.community, poller.snmpver)
    poller.ifdescr = rs['value']
    s = rs['value']
    rs = snmpget(poller.address, OIDS['ifAlias'] + '.' + poller.if_id, poller.community, poller.snmpver)
    poller.ifalias = rs['value']
    s += ': "' + rs['value'] + '"'
    print(s)
    try:
        rs = snmpget(poller.address, ('{0}.{1}'.format(OIDS['ifAdminStatus'], poller.if_id),
            '{0}.{1}'.format(OIDS['ifOperStatus'], poller.if_id)), poller.snmpver, exception=True)
    except SnmpError:
        poller.if_admin_status = None
        poller.if_op_status = None
    else:
        print rs
        poller.if_admin_status = rs['value'][0]
        poller.if_op_status = rs['value'][1]
        if not '1' in poller.if_admin_status or not '1' in poller.if_op_status:
            print 'Warning: ifAdminStatus:', poller.if_admin_status
            print 'Warning: ifOperStatus:', poller.if_op_status
    print('-' * columns)

    if not opts.maxspeed:
        poller.get_ifmaxspeed()
    else:
        poller.ifspeed_max = int(opts.maxspeed)

    speed, units = poller._convert_speed(poller.ifspeed_max)
    try:
        rs = snmpget(poller.address, OIDS['ifInErrors'] + '.' + poller.if_id,
                                            poller.community, poller.snmpver, exception=True)
    except SnmpError:
        poller.ifinerrors = '?'
    else:
        poller.ifinerrors = int(rs['value'])

    try:
        rs = snmpget(poller.address, OIDS['ifOutErrors'] + '.' + poller.if_id,
                                            poller.community, poller.snmpver, exception=True)
    except SnmpError:
        poller.ifouterrors = '?'
    else:
        poller.ifouterrors = int(rs['value'])
    
    if opts.use64bit:
        use64bit = True
    elif getattr(poller, 'ifspeed_max', 0) >= 1e9:  # try to use 64bit counters on gigabit interfaces
        use64bit = poller.if_check64()
    else:
        use64bit = False

    if use64bit:
        s = '64 |'
    else: s = ''
    print '| Spd:', speed, units + 'bit/s', '| iErr:', str(poller.ifinerrors), '| oErr:',\
                                str(poller.ifouterrors), '| Upd:', str(opts.updtime)+'s', '|', s
    
###############################################################################################################    
    #rs = poller.get_ifrate(req_delay=1, if_id = 1)
    #print rs
    #sys.exit()
###############################################################################################################    
    
    noprint = False
    stab_time = 1
    while 1:
        rows, columns = terminal_size()
        try:
            data = poller.get_ifrate(req_delay=opts.updtime, force64bit=use64bit)
        except SnmpError as ei:    # no data recieved
            # stop watching:
            #if stab_time > 600:
            #    print '\n', ei
            #    raise MyError('device is too busy or inaccessible')
            noprint = True  # wait for device to become stable
            sleep(stab_time * opts.updtime)
            if stab_time * opts.updtime < 600:
                stab_time *= 2
            #continue
        stab_time = 1
        
        in_speed = data['in_speed']
        out_speed = data['out_speed']

        if None in data:
            noprint = True
        
        if noprint is False:
            in_speed_str, in_units = poller._convert_speed(in_speed)
            out_speed_str, out_units = poller._convert_speed(out_speed)
            if round(in_speed_str, 1) < 10:
                in_speed_str = 'In:  ' + str(round(in_speed_str,1)).rjust(3) + ' ' + in_units + 'bit/s'
            else: # kick off unnecessary decimals
                in_speed_str = 'In:  ' + str(int(round(in_speed_str))).rjust(3) + ' ' + in_units + 'bit/s'
            if round(out_speed_str, 1) < 10:        
                out_speed_str = 'Out: ' + str(round(out_speed_str,1)).rjust(3) + ' ' + out_units + 'bit/s'
            else:
                out_speed_str = 'Out: ' + str(int(round(out_speed_str))).rjust(3) + ' ' + out_units + 'bit/s'
            # prepare timestamps
            if opts.histT:
                out = '|' + time.strftime('%H:%M:%S') + '|'
                i = (columns - len(in_speed_str + out_speed_str) - 4 - len(out)) // 2
            else:
                out = ''
                i = (columns - len(in_speed_str + out_speed_str) - 4) // 2

            out += in_speed_str + ' ' + progressbar(in_speed, max_val=poller.ifspeed_max, width=i)
            out += '  '
            out += out_speed_str + ' ' + progressbar(out_speed, max_val=poller.ifspeed_max, width=i)
        else:
            out = 'Collecting data...'

        # add endings for non-scrolling output
        if not (opts.hist or opts.histT):
            out += ' ' * (columns - len(out) - 1) + '\r'
        else: 
            out += ' ' * (columns - len(out) - 1) + '\n'
        sys.stdout.write(out)
        sys.stdout.flush()
        noprint = False
Exemple #2
0
def SQLcollector(address, opts):
    #print(address)
    if opts.verbose: print '* Discover type of the host...'
    rs = snmpget(address, OID["sysDescr"], opts.community, opts.snmpver)
    opts.sysdescr = rs['value']
    if opts.verbose: print opts.sysdescr
    rows, columns = terminal_size()
    if opts.verbose:
        print '* Getting interface table...'
    ifdtable = []
    table = []
    ifdtable = getifdtable(address, opts.community, opts.snmpver, opts.filter)
    if opts.list or opts.verbose:
        print 'Detailed interface list:'
        labels = ('ifIndex', 'ifName', 'ifAlias', 'ifDescr', 'ifSpeed', '64bit counters')
        for i in ifdtable: table.append([i.ifindex, i.ifname, i.ifalias, i.ifdescr, i.ifspeed, i.bit64])
        # autofit table width:
        for i in [0] + range(30, 1, -1):
            outTable = formatTable([labels] + table, separateRows=2, border='|', leftBorder='|', rightBorder='|',
                                   width=i)
            tablelen = outTable.find('\n')
            if columns - tablelen > 1: break
        print outTable
    if opts.list:
        sys.exit()

    rs = snmpget(address, OID['sysName'], opts.community, opts.snmpver, exception=False)
    opts.sysname = rs['value']
    rs = snmpget(address, OID['sysObjectID'], opts.community, opts.snmpver, exception=False)
    opts.sys_object_id = rs['value']
    #print rs.__dict__

    print (opts.sysname + ':' + opts.sys_object_id).center(columns)
    print opts.sysdescr.splitlines()[0][:columns].center(columns)
    print '-' * columns

    sql_conn = psycopg2.connect("host={0} dbname={1} user={2} password={3} port={4}".format(SQL_SERVER,
                                                                                            SQL_DATABASE, SQL_USER,
                                                                                            SQL_PASS, SQL_PORT))
    sql_cur = sql_conn.cursor()

    # check if main device table exists
    sql_cur.execute("select * from information_schema.tables where table_name=%s", (SQL_DEVTABLE,))
    if sql_cur.rowcount == 0:
        raise MyError('> "{0}" table not found!'.format(SQL_DEVTABLE))

    dev_found = False
    if not opts.force_add:
        # check if device exist!
        # find device
        sql_cur.execute("SELECT * FROM devices WHERE ip_mgmt = %s", (address,))  # check value
        if sql_cur.rowcount != 0:
            devices = sql_cur.fetchall()
            for dev in devices:
                #print dev
                if dev[6] == None:
                    dev_found = True
                    device_id = dev[0]

    if not dev_found:
        print '> Creating new device in {0}...'.format(SQL_DEVTABLE)
        sql_cur.execute("""INSERT INTO devices (ip_mgmt, community, name, sys_object_id) 
                            VALUES (%s, %s, %s, %s) RETURNING id""",
                        (address, opts.community, opts.sysname, opts.sys_object_id))
        device_id = sql_cur.fetchone()[0]
        print sql_cur.statusmessage
        sql_conn.commit()
        #sql_cur.execute("SELECT * FROM devices WHERE ip_mgmt = %s", (address,))  # get id
        #device_id = sql_cur.fetchone()[0]
    else:
        print '\n> {} is found in DB with dev_id={}! No device is added...\n'.format(address, device_id)
    #sql_cur.execute("SELECT (id) FROM devices WHERE ip_mgmt = %s", (address,))  # check value


    # open SQL_INTERFACES table:
    sql_cur.execute("SELECT * FROM information_schema.tables WHERE table_name = %s", (SQL_INTERFACES,))
    if sql_cur.rowcount == 0:
        raise MeError('> "{0}" table not found!'.format(SQL_INTERFACES))


    # delete old interface list from SQL_INTERFACES table
    #sql_cur.execute('DELETE FROM {0} WHERE device_id_fk = {1};'.format(SQL_INTERFACES, device_id))

    # get inerfaces for current device:
    sql_cur.execute("SELECT (if_index) FROM interfaces WHERE dev_id = %s", (device_id,))
    sql_iftable = sql_cur.fetchall()

    # save only new interfaces in our SQL_INTERFACES table
    print '> Trying to find new interfaces for the dev_id={0}, ip={1}:'.format(device_id, address)
    ifname_lst = [i.ifname for i in ifdtable]

    for ifitem in ifdtable:  # loop through interfaces
        # skip all filtered interfaces:
        if ifitem.iffiltered:
            print '>..skipping {0}: filtered by {1}'.format(ifitem.ifname, opts.filter)
            continue

        idname = ifitem.ifname

        # find our interface in sql database and add new if needed
        #print sql_iftable
        #print [i[0] for i in sql_iftable]
        #print ifitem.ifindex
        if [str(i[0]) for i in sql_iftable].count(str(ifitem.ifindex)) == 0:
            sql = '''INSERT INTO {0} (dev_id, if_index, if_description, if_counter_capacity, enable_collect, if_alias)
                                        VALUES (%s, %s, %s, %s, %s, %s)'''.format(SQL_INTERFACES)
            timestamp = datetime.datetime.now()
            bits = '32'
            if opts.bits == '64' and ifitem.bit64:
                bits = '64'
            vars = (device_id, ifitem.ifindex, idname, bits, 'true', ifitem.ifalias)
            sql_cur.execute(sql, vars)
            print '>..adding new interface {0} ::{1}bits'.format(idname, bits)
            print sql_cur.statusmessage
        else:
            print '>..interface {0} already exist!'.format(idname)
    sql_conn.commit()

    sql_cur.close()
    sql_conn.close()
Exemple #3
0
def main():
    parser = optparse.OptionParser(usage=__doc__)
    parser.add_option("-c",
                      help="snmp agent's community",
                      default=COMMUNITY,
                      dest="community",
                      metavar="COMMUNITY")
    parser.add_option("-v",
                      help="snmp version: default is %default",
                      default=SNMPVER,
                      dest="snmpver",
                      metavar="VERSION")
    parser.add_option("-u",
                      help="update interval: default is %default",
                      dest="updtime",
                      default=UPDTIME,
                      metavar="SECONDS")
    parser.add_option("-m",
                      help="set maximum bandwidth manually",
                      dest="maxspeed",
                      default=None,
                      metavar="BITS/S")
    parser.add_option("--64",
                      help="force to use 64 bit counters",
                      action="store_true",
                      dest="use64bit",
                      default=False)
    parser.add_option("-g",
                      "--hist",
                      action="store_false",
                      dest="hist",
                      default=True,
                      help="histogram mode")
    parser.add_option("-t",
                      action="store_true",
                      dest="histT",
                      default=False,
                      help="histogram mode with timestamps")
    parser.add_option("-l",
                      action="store_true",
                      dest="list",
                      default=False,
                      help="list index of available interfaces")
    parser.add_option("-q",
                      action="store_true",
                      dest="verbose",
                      default=False,
                      help="verbose output")
    (opts, args) = parser.parse_args()
    if len(args) < 1:
        parser.error("no address specified")

    opts.address = args[0]
    opts.updtime = int(opts.updtime)
    if len(args) > 1:
        opts.if_name = args[1]
    else:
        opts.if_name = None
    if opts.address is None:
        parser.error("no address specified")
    elif opts.community is None:
        parser.error("no community specified")


#######################################################################################################################

    if opts.verbose: print('* Trying the host {0}...'.format(opts.address))
    poller = SnmpIfInfo(opts.address, opts.community, opts.snmpver)
    poller.get_sysdescr()
    if opts.verbose: print poller.sysdescr

    rows, columns = terminal_size()
    if opts.verbose: print '* Getting interface table...'
    poller.get_ifnametable()

    if opts.if_name:
        try:
            poller.find_interface_id(opts.if_name)
        except MyError:
            pass
    if not hasattr(poller, 'if_id') or opts.verbose or opts.list:
        print 'Available interface list:'
        print '-' * columns
        print sorted(poller.ifnametable, key=poller._sort_natural)
        print '-' * columns
    if opts.list:
        from modules.mytable import formatTable
        print 'Detailed interface list:'
        iftable = poller.get_iftable()
        labels = ('ifIndex', 'ifName', 'ifAlias', 'ifDescr')
        table = []
        for i in iftable:
            table.append([i['ifid'], i['ifname'], i['ifalias'], i['ifdescr']])
        # autofit table width:
        for i in [0] + range(30, 1, -1):
            outTable = formatTable([labels] + table,
                                   separateRows=2,
                                   border='|',
                                   leftBorder='|',
                                   rightBorder='|',
                                   width=i)
            tablelen = outTable.find('\n')
            if columns - tablelen > 1:
                break
        print outTable
        sys.exit()
    if not hasattr(poller, 'if_id'):
        if opts.if_name: raise
        else: raise MyError('no interface specified')

    poller.get_sysname()
    print poller.sysname.center(columns)
    print poller.sysdescr.splitlines()[0][:columns].center(columns)
    print '-' * columns
    rs = snmpget(poller.address, OIDS['ifDescr'] + '.' + poller.if_id,
                 poller.community, poller.snmpver)
    poller.ifdescr = rs['value']
    s = rs['value']
    rs = snmpget(poller.address, OIDS['ifAlias'] + '.' + poller.if_id,
                 poller.community, poller.snmpver)
    poller.ifalias = rs['value']
    s += ': "' + rs['value'] + '"'
    print(s)
    try:
        rs = snmpget(poller.address,
                     ('{0}.{1}'.format(OIDS['ifAdminStatus'], poller.if_id),
                      '{0}.{1}'.format(OIDS['ifOperStatus'], poller.if_id)),
                     poller.snmpver,
                     exception=True)
    except SnmpError:
        poller.if_admin_status = None
        poller.if_op_status = None
    else:
        print rs
        poller.if_admin_status = rs['value'][0]
        poller.if_op_status = rs['value'][1]
        if not '1' in poller.if_admin_status or not '1' in poller.if_op_status:
            print 'Warning: ifAdminStatus:', poller.if_admin_status
            print 'Warning: ifOperStatus:', poller.if_op_status
    print('-' * columns)

    if not opts.maxspeed:
        poller.get_ifmaxspeed()
    else:
        poller.ifspeed_max = int(opts.maxspeed)

    speed, units = poller._convert_speed(poller.ifspeed_max)
    try:
        rs = snmpget(poller.address,
                     OIDS['ifInErrors'] + '.' + poller.if_id,
                     poller.community,
                     poller.snmpver,
                     exception=True)
    except SnmpError:
        poller.ifinerrors = '?'
    else:
        poller.ifinerrors = int(rs['value'])

    try:
        rs = snmpget(poller.address,
                     OIDS['ifOutErrors'] + '.' + poller.if_id,
                     poller.community,
                     poller.snmpver,
                     exception=True)
    except SnmpError:
        poller.ifouterrors = '?'
    else:
        poller.ifouterrors = int(rs['value'])

    if opts.use64bit:
        use64bit = True
    elif getattr(poller, 'ifspeed_max',
                 0) >= 1e9:  # try to use 64bit counters on gigabit interfaces
        use64bit = poller.if_check64()
    else:
        use64bit = False

    if use64bit:
        s = '64 |'
    else:
        s = ''
    print '| Spd:', speed, units + 'bit/s', '| iErr:', str(poller.ifinerrors), '| oErr:',\
                                str(poller.ifouterrors), '| Upd:', str(opts.updtime)+'s', '|', s

    ###############################################################################################################
    #rs = poller.get_ifrate(req_delay=1, if_id = 1)
    #print rs
    #sys.exit()
    ###############################################################################################################

    noprint = False
    stab_time = 1
    while 1:
        rows, columns = terminal_size()
        try:
            data = poller.get_ifrate(req_delay=opts.updtime,
                                     force64bit=use64bit)
        except SnmpError as ei:  # no data recieved
            # stop watching:
            #if stab_time > 600:
            #    print '\n', ei
            #    raise MyError('device is too busy or inaccessible')
            noprint = True  # wait for device to become stable
            sleep(stab_time * opts.updtime)
            if stab_time * opts.updtime < 600:
                stab_time *= 2
            #continue
        stab_time = 1

        in_speed = data['in_speed']
        out_speed = data['out_speed']

        if None in data:
            noprint = True

        if noprint is False:
            in_speed_str, in_units = poller._convert_speed(in_speed)
            out_speed_str, out_units = poller._convert_speed(out_speed)
            if round(in_speed_str, 1) < 10:
                in_speed_str = 'In:  ' + str(round(
                    in_speed_str, 1)).rjust(3) + ' ' + in_units + 'bit/s'
            else:  # kick off unnecessary decimals
                in_speed_str = 'In:  ' + str(int(
                    round(in_speed_str))).rjust(3) + ' ' + in_units + 'bit/s'
            if round(out_speed_str, 1) < 10:
                out_speed_str = 'Out: ' + str(round(
                    out_speed_str, 1)).rjust(3) + ' ' + out_units + 'bit/s'
            else:
                out_speed_str = 'Out: ' + str(int(
                    round(out_speed_str))).rjust(3) + ' ' + out_units + 'bit/s'
            # prepare timestamps
            if opts.histT:
                out = '|' + time.strftime('%H:%M:%S') + '|'
                i = (columns - len(in_speed_str + out_speed_str) - 4 -
                     len(out)) // 2
            else:
                out = ''
                i = (columns - len(in_speed_str + out_speed_str) - 4) // 2

            out += in_speed_str + ' ' + progressbar(
                in_speed, max_val=poller.ifspeed_max, width=i)
            out += '  '
            out += out_speed_str + ' ' + progressbar(
                out_speed, max_val=poller.ifspeed_max, width=i)
        else:
            out = 'Collecting data...'

        # add endings for non-scrolling output
        if not (opts.hist or opts.histT):
            out += ' ' * (columns - len(out) - 1) + '\r'
        else:
            out += ' ' * (columns - len(out) - 1) + '\n'
        sys.stdout.write(out)
        sys.stdout.flush()
        noprint = False