Esempio n. 1
0
    def test_v1_mv_get(self):
        print("\n")
        print(
            "---v1 multi-varbind test-------------------------------------\n")
        sess = setup_v1()

        varlist = netsnmp.VarList(netsnmp.Varbind('sysUpTime', 0),
                                  netsnmp.Varbind('sysContact', 0),
                                  netsnmp.Varbind('sysLocation', 0))
        vals = sess.get(varlist)
        print("v1 sess.get result: ", vals, "\n")
        self.assertTrue(len(vals) > 0)

        for var in varlist:
            print(var.tag, var.iid, "=", var.val, '(', var.type, ')')

        vals = sess.getnext(varlist)
        print("v1 sess.getnext result: ", vals, "\n")
        self.assertTrue(len(vals) > 0)

        for var in varlist:
            print(var.tag, var.iid, "=", var.val, '(', var.type, ')')

        varlist = netsnmp.VarList(netsnmp.Varbind('sysUpTime'),
                                  netsnmp.Varbind('sysORLastChange'),
                                  netsnmp.Varbind('sysORID'),
                                  netsnmp.Varbind('sysORDescr'),
                                  netsnmp.Varbind('sysORUpTime'))

        vals = sess.getbulk(2, 8, varlist)
        print("v1 sess.getbulk result: ", vals, "\n")
        self.assertEqual(vals, None)  # GetBulk is not supported for v1

        for var in varlist:
            print(var.tag, var.iid, "=", var.val, '(', var.type, ')')
def Disk_Controller():
    disk_controller_name_list = []
    disk_controller_status_list = []
    problem_disk_controller_list = []
    disk_controller_status_Dict = {}

    disk_controller_name_oid = str(
        ".1.3.6.1.4.1.674.10892.5.5.1.20.130.1.1.2.")
    for i in range(1, 4):
        disk_controller_name_suboid = disk_controller_name_oid + str(i)
        disk_controller_name = netsnmp.snmpget(
            netsnmp.Varbind(disk_controller_name_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(disk_controller_name[0]) != str("None"):
            disk_controller_name_list.append(disk_controller_name[0])
        else:
            break

    disk_controller_status_oid = str(
        ".1.3.6.1.4.1.674.10892.5.5.1.20.130.1.1.38.")
    for i in range(1, 4):
        disk_controller_status_suboid = disk_controller_status_oid + str(i)
        disk_controller_status = netsnmp.snmpget(
            netsnmp.Varbind(disk_controller_status_suboid),
            Version=2,
            DestHost=(hosts),
            Community=(communitys))
        if str(disk_controller_status[0]) != str("None"):
            disk_controller_status_list.append(disk_controller_status[0])
        else:
            break

    disk_controller_status_Dict = dict(
        zip(disk_controller_name_list, disk_controller_status_list))

    for (k, i) in disk_controller_status_Dict.items():
        if i != str(3):
            problem_disk_controller_list.append(k)

    if len(problem_disk_controller_list) == 0:
        for i in disk_controller_name_list:
            print i,
        print "is OK,",

    else:
        for i in problem_disk_controller_list:
            print i,
        print "is problem,",
Esempio n. 3
0
def fetchOID(host, community, graphiteroot, emcDisk, verbose):

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

    statsTable = {
        'diskperfOpsPerSecond': '1.3.6.1.4.1.12124.2.2.52.1.3',
        'diskperfInBitsPerSecond': '1.3.6.1.4.1.12124.2.2.52.1.4',
        'diskperfOutBitsPerSecond': '1.3.6.1.4.1.12124.2.2.52.1.5'
    }
    snmp = netsnmp.Session(DestHost=host, Version=2, Community=community)

    # connect and fetch the list of isilon disks
    emcDiskList = '.1.3.6.1.4.1.12124.2.2.52.1.2'
    Var = netsnmp.Varbind(emcDiskList)
    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 emcDisk:
            if vs.val not in emcDisk:
                continue

        #import pdb;pdb.set_trace()
        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
Esempio n. 4
0
    def test_v3_get(self):
        print("\n")
        sess = setup_v3()
        varlist = netsnmp.VarList(netsnmp.Varbind('sysUpTime', 0),
                                  netsnmp.Varbind('sysContact', 0),
                                  netsnmp.Varbind('sysLocation', 0))
        print("---v3 get-------------------------------------\n")
        vals = sess.get(varlist)
        print("v3 sess.get result: ", vals, "\n")
        self.assertTrue(len(vals) > 0)

        for var in varlist:
            print(var.tag, var.iid, "=", var.val, '(', var.type, ')')
        print("\n")
Esempio n. 5
0
def fetchOID(host, community, graphiteroot, virtualserver, verbose):
    if verbose:
        print >> sys.stderr, 'connecting to host: %s using community: %s' % (
            host, community)

    statsTable = {
        'gtmPoolStatPreferred': '1.3.6.1.4.1.3375.2.3.6.2.3.1.2',
        'gtmPoolStatAlternate': '1.3.6.1.4.1.3375.2.3.6.2.3.1.3',
        'gtmPoolStatFallback': '1.3.6.1.4.1.3375.2.3.6.2.3.1.4',
        'gtmPoolStatDropped': '1.3.6.1.4.1.3375.2.3.6.2.3.1.5',
        'gtmPoolStatExplicitIp': '1.3.6.1.4.1.3375.2.3.6.2.3.1.6',
        'gtmPoolStatReturnToDns': '1.3.6.1.4.1.3375.2.3.6.2.3.1.7'
    }
    snmp = netsnmp.Session(DestHost=host, Version=2, Community=community)

    # connect and fetch the list of virtual servers
    gtmPoolStatList = '.1.3.6.1.4.1.3375.2.3.6.2.3.1.1'
    Var = netsnmp.Varbind(gtmPoolStatList)
    Vars = netsnmp.VarList(Var)
    snmp.walk(Vars)
    currentTime = time.time()
    for vs in Vars:
        # vs.iid = the index of the virtualserver
        # 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 virtualservers
        # make sure we filter on those
        if virtualserver:
            if vs.val not in virtualserver:
                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, 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
Esempio n. 6
0
    def test_v3_getbulk(self):
        sess = setup_v3()
        varlist = netsnmp.VarList(netsnmp.Varbind('sysUpTime'),
                                  netsnmp.Varbind('sysORLastChange'),
                                  netsnmp.Varbind('sysORID'),
                                  netsnmp.Varbind('sysORDescr'),
                                  netsnmp.Varbind('sysORUpTime'))

        vals = sess.getbulk(2, 8, varlist)
        print("v3 sess.getbulk result: ", vals, "\n")
        self.assertTrue(len(vals) > 0)

        for var in varlist:
            print(var.tag, var.iid, "=", var.val, '(', var.type, ')')
        print("\n")
Esempio n. 7
0
def getnfs(target):
    session = netsnmp.Session(DestHost=target,
                              Version=2,
                              Community=communitystring)
    uspacevar = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.12124.1.3.2.0'))
    aspacevar = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.12124.1.3.3.0'))
    tspacevar = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.12124.1.3.1.0'))
    uspace = session.get(uspacevar)
    aspace = session.get(aspacevar)
    tspace = session.get(tspacevar)
    pspace = float(aspace[0]) / float(tspace[0]) * 100
    print "\t\t%s : used = %s : availible space = %s : free = %.2f %% " % (
        target, sizeof_fmt(int(uspace[0])), sizeof_fmt(int(aspace[0])), pspace)
    return "\t\t%s : used = %s : availible space = %s : free = %.2f %% " % (
        target, sizeof_fmt(int(uspace[0])), sizeof_fmt(int(aspace[0])), pspace)
Esempio n. 8
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
Esempio n. 9
0
	def updateOnuIpHost(self,controlid):
		#time.sleep(1)
		_vars = netsnmp.VarList(
			netsnmp.Varbind(iso,sleGponOnuHostControlRequest, '2','INTEGER'),
			netsnmp.Varbind(iso,sleGponOnuHostControlOltId, self.OLTinterface,'INTEGER'),
			netsnmp.Varbind(iso,sleGponOnuHostControlOnuId, self.ONUid,'INTEGER'),
			netsnmp.Varbind(iso,sleGponOnuHostControlId, str(controlid),'INTEGER'),
			netsnmp.Varbind(iso,sleGponOnuHostControlTimer, '0','INTEGER')
			)
		status = self._snmp_session.set(_vars)
		#time.sleep(0.5)
		if status == 1:
			result = "Success"
		else:
			result = "Failure"
		return result
Esempio n. 10
0
def snmp_get(host, credential, object_type):
    """Impelmentation of snmp get functionality

    :param object_type: mib object
    :param host: switch ip
    :param credential: the dict of credential to access switch
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'Version' not in credential or 'Community' not in credential:
        logging.error('[uitls][snmp_get] missing keywords in %s for %s',
                      credential, host)
        return None

    if credential['Version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['Version']]
        credential['Version'] = version

    varbind = netsnmp.Varbind(object_type)
    res = netsnmp.snmpget(varbind, DestHost=host, **credential)
    if not res:
        logging.error('no result found for %s %s', host, credential)
        return None

    return res[0]
Esempio n. 11
0
 def query(self):
     """
     snmpwalk
     """
     result = None
     try:
         result = netsnmp.snmpwalk(netsnmp.VarList(
             netsnmp.Varbind(self.oid, '', 10, 'INTEGER')),
                                   Version=int(self.version),
                                   DestHost=self.destHost,
                                   Community=self.community)
         print result
         if len(result) == 0:
             error = 'snmp get lldp info fail'
             if not os.path.exists(self.file):
                 os.mknod(self.file)
             with open(self.file, 'w') as f:
                 csvwriter = csv.writer(f)
                 csvwriter.writerow(
                     [self.destHost, self.community, self.oid, error])
     except Exception:
         error = 'snmp get lldp info fail'
         if not os.path.exists(self.file):
             os.mknod(self.file)
         with open(self.file, 'w') as f:
             csvwriter = csv.writer(f)
             csvwriter.writerow(
                 [self.destHost, self.community, self.oid, error])
         result = None
     return result
Esempio n. 12
0
	    def run(self):
		for id_ in self.ids4thr:
		    devline = self.devices[id_]
		    ip = devline['ip']
		    snmp_comm_this_device = snmp_wcomm
		    # Если community для устройства задано явно - переопределяем переменную
		    if devline['wcomm'] != '': snmp_comm_this_device = devline['wcomm']
		    device_model = devline['mname']
		    if device_model in oids_set:
			query = 'skipped'
			for paramname in sorted(oids_set[device_model].keys()):
			    start_time = time.time()
			    if paramname in self.WorkMetricsListS:
				current_snmp_retries = snmp_retries
				if paramname in no_retries:
				    current_snmp_retries = 0
				varlist = netsnmp.VarList(*[netsnmp.Varbind(*VarBindItem) for VarBindItem in oids_set[device_model][paramname]])
				query   = netsnmp.snmpset(*varlist, Version = 2, DestHost = ip, Community = snmp_comm_this_device, Timeout = snmp_timeout, Retries = current_snmp_retries, UseNumeric = 1)
				time.sleep(set_iter_delay)
			    # Время, затраченное на опрос
			    query_time = int((time.time()-start_time)*1000)
			    devline['time'] += query_time
			    devline['set_res'][paramname] = query
		    devline['set_timestamp'] = int(time.time())
		    self.devices[id_] = devline
Esempio n. 13
0
 def snmp_walk(self, widget):
     try:
         import netsnmp
     except:
         self.log(
             '[D2] Module netsnmp not present. You can download and install this module at this url: http://www.net-snmp.org/wiki/index.php/Python_Bindings'
         )
         return
     community = oid = version = ''
     self.c = self.wTree2.get_widget("community")
     community = self.c.get_text()
     self.c = self.wTree2.get_widget("version")
     version = self.c.get_value_as_int()
     self.c = self.wTree2.get_widget("oid")
     oid = self.c.get_text()
     self.c = self.wTree2.get_widget("snmpinfo")
     self.buffer = self.c.get_buffer()
     vars = netsnmp.VarList(netsnmp.Varbind(oid))
     res = netsnmp.snmpwalk(vars,
                            Version=version,
                            DestHost=self.host,
                            Community=community)
     nfo = ''
     for var in vars:
         nfo += "ifIndex value = %s\tifDescr value = %s\n" % (var.iid,
                                                              var.val)
     self.buffer.set_text(nfo)
Esempio n. 14
0
    def target_function(self, running, data):
        name = threading.current_thread().name
        address = "{}:{}".format(self.target, self.port)

        print_status(name, 'thread is starting...')

        while running.is_set():
            try:
                string = data.next().strip()

                bindvariable = netsnmp.Varbind(".1.3.6.1.2.1.1.1.0")
                res = netsnmp.snmpget(bindvariable,
                                      Version=1,
                                      DestHost=address,
                                      Community=string)

                if res[0] != None:
                    running.clear()
                    print_success(
                        "{}: Valid community string found!".format(name),
                        string)
                    self.strings.append(tuple([string]))
                else:
                    pass
                # print_error("{}: Invalid community string.".format(name), string)

            except StopIteration:
                break

        print_status(name, 'thread is terminated.')
Esempio n. 15
0
def snmp_test():
    var = netsnmp.Varbind(".1.3.6.1.4.1.19536.10.1.4.7.1.2")
    res = netsnmp.snmpwalk(var,
                           Version=1,
                           DestHost='192.168.1.101',
                           Community='public')
    print(res)
Esempio n. 16
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!')
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 19
0
    def _snmp_discover_personality(self):
        '''Loads netsnmp mod and attempts to discover the host's personality
        via snmp by querying sysDescr'''
        varbind = netsnmp.snmpget(
            netsnmp.Varbind('.1.3.6.1.2.1.1.1.0'),
            DestHost=self.hostname,
            Version=self.snmp_version,
            Community=self.snmp_community,
        )

        if varbind[0] is None:
            raise Error('%s: SNMP query failed' % self.hostname)

        sys_descr = varbind[0]

        for personality in PERSONALITIES:
            # skip generic personality
            if personality == 'generic':
                continue

            if re.search(PERSONALITIES[personality]['sys_descr'],
                         sys_descr,
                         flags=re.I):
                self.personality = personality
                break
        else:
            raise Error('%s: Unable to determine personality of "%s"' %
                        (self.hostname, sys_descr))
Esempio n. 20
0
    def update(self):
        try:
            # pass
            port = '4'
            index = '13'

            oid = netsnmp.Varbind('.1.3.6.1.4.1',
                                  '.2011.5.25.157.1.1.1.1.15.9', '2',
                                  'INTEGER')
            # print netsnmp.snmpset(oid,Version=1,DestHost='10.15.9.253',Community='private@it')
            print netsnmp.snmpget('.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15.5',
                                  Version=1,
                                  DestHost='10.15.9.253',
                                  Community='private@it')
            print netsnmp.snmpgetnext(
                '.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15.5',
                Version=1,
                DestHost='10.15.9.253',
                Community='private@it')
            print netsnmp.snmpwalk('.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15',
                                   Version=1,
                                   DestHost='10.15.9.253',
                                   Community='private@it')
        except Exception, err:
            print err
Esempio n. 21
0
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
Esempio n. 22
0
    def get_snmp(self, oid):
        value = netsnmp.VarList(netsnmp.Varbind(oid))

        if not self.session.get(value):
            return None
        else:
            return value[0].val
Esempio n. 23
0
def walk(sess, oid):
    ret = {}
    nextoid = oid
    offset = 0

    # Abort the walk when it exits the OID tree we are interested in
    while nextoid.startswith(oid):
        var_list = netsnmp.VarList(netsnmp.Varbind(nextoid, offset))
        sess.getbulk(nonrepeaters=0, maxrepetitions=256, varlist=var_list)
        #Sleep because the snmp walk times out //ventris
        time.sleep(1)

        if sess.ErrorStr == 'Timeout':
            raise TimeoutError('Timeout getting %s' % nextoid)
        if sess.ErrorStr != '':
            raise SnmpError('SNMP error while walking host: %s' %
                            sess.ErrorStr)

        for result in var_list:
            currentoid = '%s.%s' % (result.tag, int(result.iid))
            # We don't want to save extra oids that the bulk walk might have
            # contained.
            if not currentoid.startswith(oid):
                break
            ret[currentoid] = ResultTuple(result.val, result.type)
        # Continue bulk walk
        offset = int(var_list[-1].iid)
        nextoid = var_list[-1].tag
    return ret
Esempio n. 24
0
    def walk_snmp(self, oid):
        values = netsnmp.VarList(netsnmp.Varbind(oid))

        if not self.session.walk(values):
            return None
        else:
            return values
    def testgetaveragepower(self):
        '''snmp get AveragePower'''

        snmpvars = netsnmp.VarList(
            netsnmp.Varbind('.1.3.6.1.4.1.2011.2.235.1.1.20.3.0'))
        vals, = self.sess.get(snmpvars)
        self.assertIsNotNone(vals)
Esempio n. 26
0
        def RebootOutlet(self, command):                            
                if "Option" in command:
                        #isinstance(command["Option"],( int, long )):
                        if command["Option"].isdigit(): 
                                id = int(command["Option"])                               

                                #get number of outputs
                                snmpDevice = lib_SNMP.SNMPv2(self.ipaddr)
                                outletCount = snmpDevice.readSNMP(self.getDataDict['infeedOutletCount'])

                                if outletCount is not None:
                                        outletCount = int(outletCount)

                                if id > 0 and id <= outletCount:  
                                        self.log.printInfo("Rebooting outlet %s" % id)
                                        #outletControlAction 1.3.6.1.4.1.1718.3.2.3.1.11.1.1.1-8
                                        # readWrite ! - 0 none, 1 on, 2 off, 3 reboot
                                        oid = netsnmp.Varbind('.1.3.6.1.4.1.1718.3.2.3.1.11.1.1.' + str(id),'','3','INTEGER')
                                        res = netsnmp.snmpset(oid, Version=2, DestHost=self.ipaddr, Community='private')
                                        # res = netsnmp.snmpset(oid, version=2, hostname=self.ipaddr, community='private')

                                        return False
                        else:
                                self.log.printWarning("Given outlet was not a number")
                                return True
                else:
                        self.log.printWarning("No outlet-number was given")
                        return True  
Esempio n. 27
0
    def is_listening():
        if p.poll() is not None:
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        num_sockets = 0
        try:
            for e in os.listdir("/proc/%d/fd" % p.pid):
                try:
                    if os.readlink("/proc/%d/fd/%s" % (p.pid, e)).startswith("socket:"):
                        num_sockets += 1
                except OSError:
                    pass
        except OSError:
            if p.poll() is None:
                raise
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        if num_sockets < 2:
            return False

        import netsnmp
        var = netsnmp.Varbind("sysDescr.0")
        result = netsnmp.snmpget(var, Version=2, DestHost="127.0.0.1:1337", Community="public")
        if result is None or result[0] is None:
            return False
        return True
Esempio n. 28
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
Esempio n. 29
0
    def is_listening():
        if p.poll() is not None:
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        num_sockets = 0
        try:
            for e in os.listdir("/proc/%d/fd" % p.pid):
                try:
                    if os.readlink("/proc/%d/fd/%s" % (p.pid, e)).startswith("socket:"):
                        num_sockets += 1
                except OSError:
                    pass
        except OSError:
            if p.poll() is None:
                raise
            raise Exception("snmpsimd died. Exit code: %d" % p.poll())

        if num_sockets < 2:
            return False

        # Correct module is only available in the site
        import netsnmp  # type: ignore[import] # pylint: disable=import-error,import-outside-toplevel
        var = netsnmp.Varbind("sysDescr.0")
        result = netsnmp.snmpget(var, Version=2, DestHost="127.0.0.1:1337", Community="public")
        if result is None or result[0] is None:
            return False
        return True
Esempio n. 30
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