def snmp():
	parser = argparse.ArgumentParser()
	parser.add_argument("-v","--version",help="version 1 or 2 or 3",choices=[1,2,3],type=int)
	parser.add_argument("-ip","--ip",help="hostname/ip")
	parser.add_argument("-c","--community",help="communit name")
	parser.add_argument("-u","--v3_uname",help="v3 user name")
	parser.add_argument("-x","--privprotocol",help="v3 priv protocol ex:AES")
	parser.add_argument("-X","--privpassword",help="v3 priv password")
	parser.add_argument("-a","--authprotocol",help="v3 auth protocol")
	parser.add_argument("-A","--authpassword",help="v3 auth password")
	parser.add_argument("-l","--level",help="v3 level")
	parser.add_argument("-o","--oid",help="returns oid next to this oid")
	try:
		args = parser.parse_args()		
	except Exception:
		print "error in arguments passed"
	vars = netsnmp.VarList(netsnmp.Varbind(args.oid))
	snmpgetnext=[]
	if args.version==2 or args.version==1:
		session=netsnmp.Session(Version=2, DestHost=args.ip,Community=args.community)
		session.getnext(vars)
		for i in vars:
			print('{}.{} : {}'.format(i.tag, i.iid, i.val))	
			snmpgetnext.append('{}.{} : {}'.format(i.tag, i.iid, i.val))
		
	if args.version==3:
		session=netsnmp.Session(Version=args.version, DestHost=args.ip, SecLevel=args.level,AuthProto=args.authprotocol, AuthPass=args.authpassword, PrivProto=args.privprotocol,PrivPass=args.privpassword, SecName=args.v3_uname)
		session.getnext(vars)
		for i in vars:
			print('{}.{} : {}'.format(i.tag, i.iid, i.val))	
			snmpgetnext.append('{}.{} : {}'.format(i.tag, i.iid, i.val))
	return snmpgetnext
Example #2
0
def check_status(ip, community, snmpVersion, SecLevel, SecName, PrivPass,
                 AuthPass):
    ping = check_connect(ip)
    if snmpVersion == 2:
        session = netsnmp.Session(Version=2,
                                  DestHost=ip,
                                  Community=community,
                                  Timeout=2000,
                                  Retries=0)
    elif snmpVersion == 3:
        if SecLevel == 'authPriv':
            session = netsnmp.Session(Version=3,
                                      DestHost=ip,
                                      SecLevel=SecLevel,
                                      SecName=SecName,
                                      PrivPass=PrivPass,
                                      AuthPass=AuthPass)
        else:
            status = {'connect_status': 0, 'snmp_status': 0}
            return status
    testsnmp = netsnmp.Varbind('sysName')
    varlist = netsnmp.VarList(testsnmp)
    if ping == 0:
        status = {'connect_status': ping, 'snmp_status': 0}
        f_err.write('ping error ' + ip + '\n')
        return status
    else:
        snmp_status = session.get(varlist)
        if not snmp_status:
            snmp = 0
            f_err.write('snmp error ' + ip + '\n')
        else:
            snmp = 1
        status = {'connect_status': ping, 'snmp_status': snmp}
        return status
Example #3
0
    def __init__(self, nexenta):
        cfg = ReadConfig()

        username = cfg.get_option(nexenta['hostname'], 'snmp_user')
        password = cfg.get_option(nexenta['hostname'], 'snmp_pass')
        community = cfg.get_option(nexenta['hostname'], 'snmp_community')
        port = cfg.get_option(nexenta['hostname'], 'snmp_port')
        if not port:
            port = 161

        # If username/password use SNMP v3, else use SNMP v2.
        if username and password:
            self.session = netsnmp.Session(DestHost='%s:%s' %
                                           (nexenta['ip'], port),
                                           Version=3,
                                           SecLevel='authNoPriv',
                                           AuthProto='MD5',
                                           AuthPass=password,
                                           SecName=username)
        elif community:
            self.session = netsnmp.Session(DestHost='%s:%s' %
                                           (nexenta['ip'], port),
                                           Version=2,
                                           Community=community)
        else:
            raise CritError("Incorrect SNMP info configured for %s" %
                            nexenta['hostname'])
Example #4
0
File: snmp.py Project: dalini/dhmon
    def _snmp_session(self, vlan=None, timeout=1000000, retries=3):
        # Since pickle will import this module we do not want to drag netsnmp into
        # this on every load. Load it when we need it.
        global _NETSNMP_CACHE
        first_load = False
        if _NETSNMP_CACHE is None:
            first_load = True
            import netsnmp
            _NETSNMP_CACHE = netsnmp
        else:
            netsnmp = _NETSNMP_CACHE

        if first_load:
            # Loading MIBs can be very noisy, so we close stderr
            # Ideally we would just call netsnmp_register_loghandler but that isn't
            # exported :-(
            stderr = os.dup(sys.stderr.fileno())
            null = os.open(os.devnull, os.O_RDWR)
            os.close(sys.stderr.fileno())
            os.dup2(null, sys.stderr.fileno())
            os.close(null)

        if self.version == 3:
            context = ('vlan-%s' % vlan) if vlan else ''
            session = netsnmp.Session(Version=3,
                                      DestHost=self._full_host,
                                      SecName=self.user,
                                      SecLevel=self.sec_level,
                                      Context=context,
                                      AuthProto=self.auth_proto,
                                      AuthPass=self.auth,
                                      PrivProto=self.priv_proto,
                                      PrivPass=self.priv,
                                      UseNumeric=1,
                                      Timeout=timeout,
                                      Retries=retries), netsnmp
        else:
            community = ('%s@%s' %
                         (self.community, vlan)) if vlan else self.community
            session = netsnmp.Session(Version=self.version,
                                      DestHost=self._full_host,
                                      Community=community,
                                      UseNumeric=1,
                                      Timeout=timeout,
                                      Retries=retries), netsnmp

        if first_load:
            # Restore stderr
            os.dup2(stderr, sys.stderr.fileno())
            os.close(stderr)
        return session
Example #5
0
    def get(host=None, port=None, community=None, metrics=None):
        assert host and port and community and metrics

        oids = []
        for k, v in oids_data.iteritems():
            if k in metrics:
                for kk, vv in v.iteritems():
                    oids.append(vv)

        import netsnmp
        session = netsnmp.Session(DestHost='%s:%s' % (host, port),
                                  Version=1,
                                  Community=community,
                                  Timeout=2000000)
        Vars = netsnmp.VarList(*oids)

        snmp_data = dict(
            (oid, val) for oid, val in zip(oids, session.get(Vars)))

        data = {}
        for metric_name in metrics:
            if metric_name not in oids_data:
                continue
            for metric in oids_data[metric_name].keys():
                try:
                    value = float(snmp_data[oids_data[metric_name][metric]])
                except:
                    value = None
                data.setdefault(metric_name, {}).setdefault(metric, value)

        return data
Example #6
0
def getconf_eltex(host, swuser, swpassword, snmp_comm):
    snmp_session = netsnmp.Session(DestHost=host,
                                   Version=2,
                                   Community=snmp_comm)
    snmp_vars = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.1.5.0'))
    sysname = snmp_session.get(snmp_vars)
    sysname = str(sysname[0].decode('utf-8'))
    tn = telnetlib.Telnet(host, 23, 3)
    tn.read_until(b"User Name:")
    tn.write(swuser.encode('utf-8') + b"\n")
    tn.read_until(b"Password:"******"\n")
    time.sleep(2)
    output = tn.read_some()
    output = output.strip()
    if "authentication failed" in output.decode('utf-8'):
        tn.close()
        print("Bad password on " + host)
    else:
        today = str(date.today())
        filename = str(sysname + "-" + today)
        tn.write(b"copy startup-config tftp://192.168.1.100/conf/noc-backup/" +
                 filename.encode('utf-8') + b"\n")
        tn.close()
        print('Backup for ' + sysname + ' OK!')
Example #7
0
def fetchOID(host, community, graphiteroot, backend, verbose):

    if verbose:
        print >> sys.stderr, 'connecting to host: %s using community: %s' % (
            host, community)

    statsTable = {
        'bytesIn': '1.3.6.1.4.1.29385.106.1.1.8',
        'bytesOut': '1.3.6.1.4.1.29385.106.1.1.9',
        'hsrp_1xx': '1.3.6.1.4.1.29385.106.1.1.39',
        'hsrp_2xx': '1.3.6.1.4.1.29385.106.1.1.40',
        'hsrp_3xx': '1.3.6.1.4.1.29385.106.1.1.41',
        'hsrp_4xx': '1.3.6.1.4.1.29385.106.1.1.42',
        'hsrp_5xx': '1.3.6.1.4.1.29385.106.1.1.43',
        'hsrp_other': '1.3.6.1.4.1.29385.106.1.1.44',
        'responseErrors': '1.3.6.1.4.1.29385.106.1.1.14',
        'sessionCurrent': '1.3.6.1.4.1.29385.106.1.1.4',
        'sessionLimit': '1.3.6.1.4.1.29385.106.1.1.6',
        'sessionMax': '1.3.6.1.4.1.29385.106.1.1.5',
        'totalSessions': '1.3.6.1.4.1.29385.106.1.1.7'
    }
    snmp = netsnmp.Session(DestHost=host, Version=2, Community=community)

    # connect and fetch the list of virtual servers
    backendList = '.1.3.6.1.4.1.29385.106.1.1.0'
    Var = netsnmp.Varbind(backendList)
    Vars = netsnmp.VarList(Var)
    snmp.walk(Vars)
    currentTime = time.time()
    for vs in Vars:
        # vs.iid = the index of the zone
        # vs.tag = leaf identifier e.g. 'zone name
        # vs.val = name of virtual server
        # vs.type = snmp data type, e.g. counter, integer, etc

        # if we specified a list of zones
        # make sure we filter on those
        if backend:
            if vs.val not in backend:
                continue

        #import pdb;pdb.set_trace()
        for type in statsTable:
            try:
                #oid = statsTable[type] + "." + vs.iid
                oid = statsTable[type] + '.' + vs.tag.rsplit('.', 2)[1] + '.0'
                head, tail = oid.rsplit('.', 1)
                vars = netsnmp.VarList(netsnmp.Varbind(head, tail))
                result = [x[0] for x in snmp.get(vars)]
                result = float(x)
                if verbose:
                    print >> sys.stderr, '%s %s = %s' % (vs.val, type, result)
                #currentTime = time.time()
                datapoint = '%s.%s.%s' % (graphiteroot, vs.val, type)
                package.append((datapoint, (currentTime, result)))
            except Exception as uhoh:
                print >> sys.stderr, "could not get oid: %s" % uhoh
                #sys.exit(1)

    return package, currentTime, result
Example #8
0
 def __init__(self,ip=''):
     """
     init function, initial with DUT ip
     """
     self.tnVclMacBasedVlanId=('.1.3.6.1.4.1.868.2.5.4.1.8.1.1.1.2','VlanIndex','read-create')
     self.tnVclMacBasedPortMember=('.1.3.6.1.4.1.868.2.5.4.1.8.1.1.1.3','PortList','read-create')
     self.tnVclMacBasedUser=('.1.3.6.1.4.1.868.2.5.4.1.8.1.1.1.4','INTEGER','read-only')
     self.tnVclMacBasedRowStatus=('.1.3.6.1.4.1.868.2.5.4.1.8.1.1.1.5','RowStatus','read-create')
     self.tnVclProtoBasedGroupMapProtocol=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.2','INTEGER','read-create')
     self.tnVclProtoBasedGroupMapEtherTypeVal=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.3','INTEGER','read-create')
     self.tnVclProtoBasedGroupMapSnapOui=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.4','EightOTwoOui','read-create')
     self.tnVclProtoBasedGroupMapSnapPid=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.5','INTEGER','read-create')
     self.tnVclProtoBasedGroupMapLlcDsap=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.6','INTEGER','read-create')
     self.tnVclProtoBasedGroupMapLlcSsap=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.7','INTEGER','read-create')
     self.tnVclProtoBasedGroupMapRowStatus=('.1.3.6.1.4.1.868.2.5.4.1.8.2.1.1.8','RowStatus','read-create')
     self.tnVclProtoBasedVlanMapPortMember=('.1.3.6.1.4.1.868.2.5.4.1.8.2.2.1.2','PortList','read-create')
     self.tnVclProtoBasedVlanMapRowStatus=('.1.3.6.1.4.1.868.2.5.4.1.8.2.2.1.3','RowStatus','read-create')
     self.tnVclIpSubnetBasedIpAddr=('.1.3.6.1.4.1.868.2.5.4.1.8.3.1.1.2','IpAddress','read-create')
     self.tnVclIpSubnetBasedMaskLen=('.1.3.6.1.4.1.868.2.5.4.1.8.3.1.1.3','INTEGER','read-create')
     self.tnVclIpSubnetBasedVlanId=('.1.3.6.1.4.1.868.2.5.4.1.8.3.1.1.4','VlanIndex','read-create')
     self.tnVclIpSubnetBasedPortMember=('.1.3.6.1.4.1.868.2.5.4.1.8.3.1.1.5','PortList','read-create')
     self.tnVclIpSubnetBasedRowStatus=('.1.3.6.1.4.1.868.2.5.4.1.8.3.1.1.6','RowStatus','')
     self.ip=ip
     ret = ispingable(ip)
     if ( ret == True ):
         self.sess=netsnmp.Session(Version=2,DestHost=self.ip,Community='private')
         print "vcl is inited in :" + ip
     else:
         print ip + "is not pingable!"
Example #9
0
    def netSnmpWalker(self,num):
        while True:
            #print self.taskq.qsize()
            try:
                host, oid=self.taskq.get(block=False) 
                oidname = self.oids[oid]
                logging.debug('%s Thread [%s] take a task : [%s-%s]. Remaining Task:[%s]' % (time.time(),num,host,oidname,self.taskq.qsize()))
                session = netsnmp.Session(
                    Community='public',
                    Version = 2, 
                    DestHost = host, 
                    Timeout = 10000000,   
                    Retries = 3,   
                )
                var_list = netsnmp.VarList()
                var_list.append(netsnmp.Varbind(oid))

                ret = session.walk(var_list)
                logging.debug('%s Thread [%s] :%s [%s] walk finished.' % (time.time(),num,host,oidname))
                #self.bar.cursor.restore()
                #self.bar.draw(value=self.taskq.qsize())

                for i in var_list:
                    try:
                        self.results[host][i.iid][i.tag]=i.val
                        #self.results.append({'host':host,'oid':oid,'ifdesc':self.ports[host][i.iid]['name'],'tag':i.tag,'ifindex':i.iid,'value':i.val})
                    except Exception, e:
                        #logging.error(e)
                        pass

            except Queue.Empty:
                break
Example #10
0
def get_metrics(host, port, community, metrics):
    assert host, 'host'
    assert port, 'port'
    assert community, 'community'
    assert metrics, 'metrics'

    oids = []
    for k, v in OIDS.iteritems():
        if k in metrics:
            for kk, vv in v.iteritems():
                oids.append(vv)
    if not oids:
        return dict()
    session = netsnmp.Session(DestHost='%s:%s' % (host, port),
                              Version=1,
                              Community=community,
                              Timeout=2500000)
    Vars = netsnmp.VarList(*oids)
    snmp_data = dict((o, v) for o, v in zip(oids, session.get(Vars)))
    data = dict()
    for metric_name in metrics:
        if metric_name not in OIDS:
            continue
        for metric in OIDS[metric_name].keys():
            try:
                value = float(snmp_data[OIDS[metric_name][metric]])
            except:
                value = None
            data.setdefault(metric_name, {}).setdefault(metric, value)
    return data
Example #11
0
def worker_snmpwalk(entity):
    ''' worker called by snmpwalk function. operates on a single
    node-mib object '''

    target = entity['target']
    oid = entity['oid']

    print('Getting %s from %s ' % (oid, target))

    mysession = netsnmp.Session(
        Version=entity['version'],
        DestHost=target,
        Community=entity['community'],
        UseNumeric=1,
    )

    vars = netsnmp.VarList(netsnmp.Varbind(oid))
    result = mysession.walk(vars)

    # -- Format and returns result
    results = []
    for i in vars:
        i.hostname = target
        i.oid = oid
        i.tag = "%s.%s" % (i.tag, i.iid)
        results.append(i)

    return results
Example #12
0
def get_detailed_subs():
    """
    Get detailed subs

    OID : .1.3.6.1.4.1.9.9.786.1.1.1.1.22
    This object indicates the NAS port-identifier identifying the
    port on the NAS providing access to the subscriber.

    OID : .1.3.6.1.4.1.9.9.786.1.1.1.1.23
    This object indicates the domain associated with the
    subscriber.

    OID : .1.3.6.1.4.1.9.9.786.1.1.1.1.24
    This object indicates the username identifying the subscriber.

    This function collect information (NAS port, domain and username) about subscribers.
    """

    for h in data['hosts']:
        ip = data['hosts'][h]['ip']
        var_oid_22 = netsnmp.Varbind(OID_22)
        var_oid_23 = netsnmp.Varbind(OID_23)
        var_oid_24 = netsnmp.Varbind(OID_24)
        vars_list = netsnmp.VarList(var_oid_22, var_oid_23, var_oid_24)
        session = netsnmp.Session(DestHost=ip, Version=2, Community=key)
        session.UseLongNames = 1
        for i in range(data['hosts'][h]['nb_sub']):
            reply = session.getnext(vars_list)
            result.append({
                'vlan': (int(reply[0].split('/')[-1].split('.')[0])),
                'domain': (reply[1].split('.', 1)[1]),
                'user': (reply[2])
            })
Example #13
0
 def get(self, port=None, cfg=None, timeout=0):
     work_oids = {'t': 16, 'h': 17}
     wo = work_oids.get(port)
     if wo is None: return None
     snmp_oid = 'iso.3.6.1.4.1.3854.1.2.2.1.%u.1.3.%u' % (
         wo, self.sensor_port - 1)
     _timeout = timeout / self.snmp_tries
     if netsnmp:
         try:
             sess = netsnmp.Session(Version=1,
                                    DestHost=self.snmp_host,
                                    RemotePort=self.snmp_port,
                                    Community=self.community,
                                    Timeout=int(_timeout * 1000000),
                                    Retries=self.snmp_tries - 1)
             return sess.get(netsnmp.VarList(snmp_oid))[0].decode()
         except:
             log_traceback()
             return None
     else:
         return snmp.get(snmp_oid,
                         self.snmp_host,
                         self.snmp_port,
                         self.community,
                         _timeout,
                         self.snmp_tries - 1,
                         rf=int,
                         snmp_ver=1)
    def setUp(self):
        self.sess = netsnmp.Session(Version=self.snmpver,
                                    DestHost=self.ipstr,
                                    Community=self.community)

        self.sess.UseEnums = 1
        self.sess.UseLongNames = 1
Example #15
0
def session_v2(host, community):
    return netsnmp.Session(Version=2,
                           DestHost=host,
                           Community=community,
                           UseNumeric=1,
                           Timeout=10000000,
                           Retries=3)
Example #16
0
 def create_session(self, timeout):
     return netsnmp.Session(Version=2,
                            DestHost=self.host,
                            RemotePort=self.port,
                            Community=self.community,
                            Timeout=int(timeout * 1000000),
                            Retries=self.retries)
Example #17
0
def do_snmpquery(snmpcmd, oid_to_get, snmpget):
    """Do an SNMP query
 
    Args:
        snmpcmd: SNMP variables required to do SNMP queries on device
        oid_to_get: OID to walk
        snmpget: Flag determining whether to do a GET or WALK
 
    Returns:
        Dictionary of tuples (OID, value)
    """

    # Initialize variables
    return_results = {}
    results_objs = False
    session = False

    # Get OID
    try:
        session = netsnmp.Session(DestHost=snmpcmd['ipaddress'],
                                  Version=snmpcmd['version'],
                                  Community=snmpcmd['community'],
                                  SecLevel='authPriv',
                                  AuthProto=snmpcmd['authprotocol'],
                                  AuthPass=snmpcmd['authpassword'],
                                  PrivProto=snmpcmd['privprotocol'],
                                  PrivPass=snmpcmd['privpassword'],
                                  SecName=snmpcmd['secname'],
                                  UseNumeric=True)
        results_objs = netsnmp.VarList(netsnmp.Varbind(oid_to_get))

        if snmpget:
            session.get(results_objs)
        else:
            session.walk(results_objs)

    except Exception as exception_error:
        # Check for errors and print out results
        print('ERROR: Occurred during SNMPget for OID %s from %s: '
              '(%s)') % (oid_to_get, snmpcmd['ipaddress'], exception_error)
        sys.exit(2)

    # Crash on error
    if (session.ErrorStr):
        print(
            'ERROR: Occurred during SNMPget for OID %s from %s: '
            '(%s) ErrorNum: %s, ErrorInd: %s') % (
                oid_to_get, snmpcmd['ipaddress'], session.ErrorStr,
                session.ErrorNum, session.ErrorInd)
        sys.exit(2)

    # Construct the results to return
    for result in results_objs:
        if is_number(result.val):
            return_results[('%s.%s') % (result.tag, result.iid)] = (float(
                result.val))
        else:
            return_results[('%s.%s') % (result.tag, result.iid)] = (result.val)

    return return_results
Example #18
0
    def __get_oid(self, oid, index=""):

        if index != "":
            snmp_community_index = self.__snmp_community + "@" + index
        else:
            snmp_community_index = self.__snmp_community

        oid_varlist = netsnmp.VarList(netsnmp.Varbind(oid))

        session = netsnmp.Session(DestHost=self.__ip_address,
                                  Version=2,
                                  Community=snmp_community_index,
                                  Retries=1)
        session.UseLongNames = 1
        session.UseNumeric = 1

        res = session.walk(oid_varlist)

        result_dict = {}
        i = 0
        for var in oid_varlist:
            if var.tag != None:
                oid_suffix = var.tag.replace(oid, "") + "." + var.iid

                if oid_suffix[:1] == ".":
                    oid_suffix = oid_suffix[1:]
                result_dict[oid_suffix] = res[i]
                i += 1

        return result_dict
Example #19
0
def main(args):  # pragma: no cover
    logging.basicConfig(format='%(levelname)s: %(message)s',
                        level=logging.INFO)
    options = parse_args(args)

    with open(options.community_file) as community_file:
        community = community_file.read().strip()

    with open(options.switch_config_file) as config:
        switch_config = models.load_switch_config(config)

    # Version "2" means "2c".
    session = netsnmp.Session(DestHost=options.hostname,
                              Version=2,
                              Community=community)
    discover_session = discovery.DiscoverySession(
        simple_session.SimpleSession(session), switch_config)

    if options.command == 'collectd-snmp-config':
        output = generate_collectd_snmp_config(discover_session,
                                               options.hostname, community)

    elif options.command == 'update-snmp-community':
        output = update_snmp_community(discover_session, options.hostname,
                                       switch_config, community)

    sys.stdout.write(output + '\n')
    sys.stdout.flush()
Example #20
0
def getOid(oid):
    session = netsnmp.Session(DestHost=cmIP, Version=2, Community='private')
    vars = netsnmp.VarList(netsnmp.Varbind(oid))
    #print( session.get(vars) )
    value = (session.get(vars))
    #value = value.replace("(","") ; value = value.replace(")","") ; value = value.replace("'","") ; value = value.replace(",","") ## Clean up the string
    return value
Example #21
0
def redbackSNMPWalk(data, ip, version, community):
    """
    Call a snmp walk on the designated REDBACK device (ip), retrieve list of connected subscriber
    :param ip:
    :param version:
    :param community:
    :return Vars: List of OID where usernames are encoded
    """
    session = netsnmp.Session(DestHost=ip,
                              Version=version,
                              Community=community)
    session.UseLongNames = 1
    oid = ".1.3.6.1.4.1.2352.2.27.1.1.1.1.3"
    var = netsnmp.Varbind(oid)
    vars_list = netsnmp.VarList(var)
    logging.debug("--- %s seconds ---" % (time.time() - start_time))
    logging.debug(f'Snmp walk to {ip}')
    subscribers = (session.walk(vars_list))
    i = 0
    for sub in subscribers:
        subtype = redbackVlanFind(sub)
        user = redbackLoginDecode(vars_list[i].tag)
        realm = ".".join(user.split('@')[1].split('.')[1:3])
        if subtype != 0:
            subtype = subtype
        else:
            subtype = loginClassify(data, realm)
        connected_logins.append(
            (user, psycopg2.TimestampFromTicks(time.time() // 1),
             psycopg2.TimestampFromTicks(time.time() // 1), True, subtype,
             True))
        i += 1
Example #22
0
def snmpGet(host, oid):
    session = netsnmp.Session(Version=2,
                              DestHost=host,
                              Community=snmp_community)

    results_objs = netsnmp.VarList(netsnmp.Varbind(oid))
    session.get(results_objs)
    return results_objs
Example #23
0
def setup_v3():
    sess = netsnmp.Session(**snmp_dest(Version=3,
                                       SecLevel='authPriv',
                                       SecName='initial',
                                       PrivPass='******',
                                       AuthPass='******'))
    sess.UseSprintValue = 1
    return sess
Example #24
0
 def get_v2_session(self, host, version_ops):
     version_ops.setdefault('community', 'public')
     version_ops.setdefault('retries', 3)
     session = netsnmp.Session(DestHost=host,
                               Version=2,
                               Community=version_ops['community'],
                               Retries=int(version_ops['retries']))
     return session
Example #25
0
def GetSNMPData(IP, oid, community, VLAN):
    #Create SNMP session with device IP and return SNMP Data as list of the objects
    SNMPData = netsnmp.VarList(netsnmp.Varbind(oid))
    session = netsnmp.Session(DestHost=IP,
                              Version=2,
                              Community=community + VLAN)
    session.walk(SNMPData)
    return SNMPData
Example #26
0
	def __init__(self,oltip,snmpCommunity):
		self._snmp_session = netsnmp.Session(DestHost=oltip, Version = 2,Community = snmpCommunity, UseNumeric=1, Timeout=10000000)
		self.oltip = oltip
		self.snmpCommunity = snmpCommunity
		#print self._snmp_session 
		self.activeOlt= self.getActiveOltID()
		self.dbase = databaseGpon(databaseVars['address'],databaseVars['user'],databaseVars['password'],databaseVars['database'])
		print self.activeOlt
Example #27
0
    def get_data(self, connection_info, metric):
        '''
        type connection_info: list of strings
        param connection_info: List [host, port, community]

        type task: list of strings
        param task: List [cpu | mem | la | net] io - not supported by snmp strategy

        return: dictionary { 
                'cpu':{
                        'user':1234,
                        'nice':1234,
                        ...}
                'la':{
                        'la1':0.1,
                        ...}
                'mem':{
                        'swap':12345,
                        ...}
                'net':{
                        'in':12345,
                        'out':12345}}
        '''

        host = connection_info[0]
        port = connection_info[1]
        community = connection_info[2]

        oids = []
        for metric_name in metric:
            oids += oids_data[metric_name].values()

        session = netsnmp.Session(DestHost='%s:%s' % (host, port),
                                  Version=1,
                                  Community=community)
        Vars = netsnmp.VarList(*oids)

        snmp_data = dict(
            (oid, val) for oid, val in zip(oids, session.get(Vars)))

        def _convert_from_str(value):
            if type(value) is str:
                if '.' in value:
                    return float(value)
                else:
                    return int(value)
            else:
                return 'U'

        for oid, value in snmp_data.iteritems():
            snmp_data[oid] = _convert_from_str(value)

        data = {}
        for metric_name in metric:
            for metric in oids_data[metric_name].keys():
                data.setdefault(metric_name, {}).setdefault(
                    metric, snmp_data[oids_data[metric_name][metric]])
        return data
def fetchOID(host, community, graphiteroot, interface, verbose):

    if verbose:
        print >> sys.stderr, 'connecting to host: %s using community: %s' % (
            host, community)

    statsTable = {
        'sysInterfaceStatPktsIn': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.2',
        'sysInterfaceStatBytesIn': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.3',
        'sysInterfaceStatPktsOut': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.4',
        'sysInterfaceStatBytesOut': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.5',
        'sysInterfaceStatMcastIn': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.6',
        'sysInterfaceStatMcastOut': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.7',
        'sysInterfaceStatErrorsIn': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.8',
        'sysInterfaceStatErrorsOut': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.9',
        'sysInterfaceStatDropsIn': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.10',
        'sysInterfaceStatDropsOut': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.11',
        'sysInterfaceStatCollisions': '1.3.6.1.4.1.3375.2.1.2.4.4.3.1.12'
    }
    snmp = netsnmp.Session(DestHost=host, Version=2, Community=community)

    # connect and fetch the list of virtual servers
    interfaceList = '.1.3.6.1.4.1.3375.2.1.2.4.1.2.1.1'
    Var = netsnmp.Varbind(interfaceList)
    Vars = netsnmp.VarList(Var)
    snmp.walk(Vars)
    currentTime = time.time()
    for vs in Vars:
        # vs.iid = the index of the interface
        # vs.tag = leaf identifier e.g. 'ltmVirtualServName'
        # vs.val = name of virtual server
        # vs.type = snmp data type, e.g. counter, integer, etc

        # if we specified a list of interfaces
        # make sure we filter on those
        if interface:
            if vs.val not in interface:
                continue

        for type in statsTable:
            try:
                oid = statsTable[type] + "." + vs.iid
                head, tail = oid.rsplit('.', 1)
                vars = netsnmp.VarList(netsnmp.Varbind(head, tail))
                result = [x[0] for x in snmp.get(vars)]
                result = float(x)
                if verbose:
                    print >> sys.stderr, '%s %s = %s' % (vs.val, type, result)
                #currentTime = time.time()
                datapoint = '%s.%s.%s' % (graphiteroot, vs.val.replace(
                    '.', '-'), type)
                package.append((datapoint, (currentTime, result)))
            except Exception as uhoh:
                print >> sys.stderr, "could not get oid: %s" % uhoh
                #sys.exit(1)

    return package, currentTime, result
Example #29
0
    def get(connection_info, metrics):
        """
        :type connection_info: dictionary 
        :param connection_info: {'host':host, 'port':port, 'community':community}

        :type metrics: list of strings
        :param metrics: list ['cpu', 'mem', 'la', 'net', 'io']

        :rtype: dictionary
        :returns: { 
                'cpu':{
                        'user':value,
                        'nice':value,
                        ...}
                'la':{
                        'la1':value,
                        ...}
                'mem':{
                        'swap':value,
                        ...}
                'net':{
                        'in':value,
                        'out':value}}
        """

        host = connection_info['host']
        port = connection_info['port']
        community = connection_info['community']

        oids = []
        for k, v in oids_data.iteritems():
            if k in metrics:
                for kk, vv in v.iteritems():
                    oids.append(vv)

        session = netsnmp.Session(DestHost='%s:%s' % (host, port),
                                  Version=1,
                                  Community=community,
                                  Timeout=1000000)
        Vars = netsnmp.VarList(*oids)

        snmp_data = dict(
            (oid, val) for oid, val in zip(oids, session.get(Vars)))

        data = {}
        for metric_name in metrics:
            if metric_name not in oids_data:
                continue
            for metric in oids_data[metric_name].keys():
                try:
                    value = float(snmp_data[oids_data[metric_name][metric]])
                except Exception:
                    value = None
                data.setdefault(metric_name, {}).setdefault(metric, value)

        return data
Example #30
0
        def __init__(self, DestHost):
            self.log = lib_Log.Log(PrintToConsole=True)
            self.Error = False                
            self.log.increaseLevel()                
            self.destHost = DestHost

            #new from here
            self.community = 'public'
            self.remotePort = 161
            self.snmpVersion = 2 #2 => 2c

            self.tables = {}
            
            self.snmpSession = netsnmp.Session(Version=self.snmpVersion,
                                                DestHost=self.destHost, 
                                                Community=self.community,
                                                RemotePort = self.remotePort,
                                                Timeout = 500000, #micro-sec
                                                Retries = 2,
                                                UseNumeric = 1,  #using OIDs                                                                                          
                                                )

            
            self.oidConversion = {}
                                     

            self.textualConversion = {}
            self.textualConversion['ifMib_ifAdminStatus']                           = {1 : 'up',    2: 'down',  3: 'testing'    }
            self.textualConversion['ifMib_ifOperStatus']                            = {1 : 'up',    2: 'down',  3: 'testing',   4: 'unknown',   5: 'dormant',   6: 'notPresent',    7: 'lowerLayerDown' }
            self.textualConversion['ifMib_IANAifType']                              = {1 : 'other', 6: 'ethernetCsmacd',        33: 'rs232',    53: 'propVirtual'     }
            self.textualConversion['PowerEthernetMib_pethPsePortAdminEnable']       = {1 : 'true',  2: 'false'    }
            self.textualConversion['PowerEthernetMib_pethPsePortDetectionStatus']   = {1 : 'disabled',          2: 'searching', 3: 'deliveringPower', 4: 'fault', 5: 'test', 6: 'otherFault'}
            self.textualConversion['PowerEthernetMib_pethMainPseOperStatus']        = {1 : 'on',    2: 'off',  3: 'faulty'    }
            self.textualConversion['EntityMib_entPhysicalClass']                    = {1: 'other', 2: 'unkown', 3: 'chassis', 4: 'backplane', 5: 'container', 6: 'powerSupply', 7: 'fan', 8: 'sensor', 9: 'module', 10: 'port', 11: 'stack', 12: 'cpu'}
            self.textualConversion['QBridgeMib_dot1qVlanStatus']                    = {1: 'other', 2: 'permanent', 3: 'dynamicGvrp'}

            #general SNMPv2MIB definition
            self.oidConversion.update({
                                '.1.3.6.1.2.1.1.1' : {'name': 'sysDescr'},
                                '.1.3.6.1.2.1.1.2' : {'name': 'sysObjectID'},
                                '.1.3.6.1.2.1.1.3' : {'name': 'sysUptime'},
                                '.1.3.6.1.2.1.1.4' : {'name': 'sysContact'},
                                '.1.3.6.1.2.1.1.5' : {'name': 'sysName'},
                                '.1.3.6.1.2.1.1.6' : {'name': 'sysLocation'},
                                '.1.3.6.1.2.1.1.7' : {'name': 'sysServices'},
                            })
                             
            self.SNMPv2MIB_varList = netsnmp.VarList(
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.1'),
                                                        #netsnmp.Varbind('.1.3.6.1.2.1.1.2'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.3'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.4'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.5'),
                                                        netsnmp.Varbind('.1.3.6.1.2.1.1.6'),
                                                        #netsnmp.Varbind('.1.3.6.1.2.1.1.7'),                                                        
                                                        )