Пример #1
0
 def test_get_multiple_return_binds(self):
     """
     A "GET" response should only return one varbind.
     """
     data = readbytes('get_sysoid_01_error.hex')
     with patch('puresnmp.send') as mck:
         mck.return_value = data
         with self.assertRaisesRegex(SnmpError, 'varbind'):
             get('::1', 'private', '1.2.3')
Пример #2
0
 def test_get_non_existing_oid(self):
     """
     A "GET" response on a non-existing OID should raise an appropriate
     exception.
     """
     data = readbytes('get_non_existing.hex')
     with patch('puresnmp.send') as mck:
         mck.return_value = data
         with self.assertRaises(NoSuchOID):
             get('::1', 'private', '1.2.3')
Пример #3
0
 def test_get_call_args(self):
     """
     Test the call arguments of "get"
     """
     data = readbytes('dummy.hex')  # any dump would do
     packet = Sequence(Integer(Version.V2C), OctetString('public'),
                       GetRequest(0, ObjectIdentifier(1, 2, 3)))
     with patch('puresnmp.send') as mck, \
             patch('puresnmp.get_request_id') as mck2:
         mck2.return_value = 0
         mck.return_value = data
         get('::1', 'public', '1.2.3')
         mck.assert_called_with('::1', 161, bytes(packet), timeout=2)
Пример #4
0
def cisco_ios(IP, COMMUNITY):
    from puresnmp import table
    from puresnmp import get
    import pandas as pd
    oid_name = "1.3.6.1.4.1.9.9.23.1.3.4.0"
    oid_if = "1.3.6.1.4.1.9.9.23.1.1.1.1"
    oid_cdp = "1.3.6.1.4.1.9.9.23.1.2.1"
    column_names = [
        "local", "local_if", "remote", "remote_if", "remote_ip", "remote_model"
    ]
    df_result = pd.DataFrame(columns=column_names)
    try:
        local_name = get(IP, COMMUNITY, oid_name)
        local_name = local_name.decode()
        interfaces = table(IP, COMMUNITY, oid_if)
        neighbors = table(IP, COMMUNITY, oid_cdp)
        for neighbor in neighbors:
            interface = interfaces[0]
            new_row = {
                "local": local_name,
                "local_if": interface[str(int(float(neighbor['0'])))].decode(),
                "remote": neighbor['6'].decode(),
                "remote_if": neighbor['7'].decode(),
                "remote_ip": iphex(neighbor['4'].hex()),
                "remote_model": neighbor['8'].decode()
            }
            df_result = df_result.append(new_row, ignore_index=True)
        return df_result
    except:
        #print ("error en: " + IP)
        return df_result
Пример #5
0
def fletcher(oi):

    result = get(agip, com, oi, port=po)
    value = result
    ti4 = ti1()  #Time of recieving the value
    print(ti4)
    n = n + 1  #Controller variable from dummy
    if n == 3:
        n = n - 2

    if n == 1:
        ti2 = ti4
        a = value

    if n == 1 and troll != 1:
        ti2 = ti4
        a = value
        fin = rate12(a, b, t12, t13)
        print(fin, end=" | ")

    if n == 2:
        ti3 = ti4
        b = value
        fin = rate12(a, b, ti2, ti3)
        print(fin, end=" | ")
Пример #6
0
 def test_get_oid(self):
     data = readbytes('get_sysoid_01.hex')
     expected = ('1.3.6.1.4.1.8072.3.2.10')
     with patch('puresnmp.send') as mck:
         mck.return_value = data
         result = get('::1', 'private', '1.2.3')
     self.assertEqual(result, expected)
Пример #7
0
 def test_get_string(self):
     data = readbytes('get_sysdescr_01.hex')
     expected = (b'Linux d24cf7f36138 4.4.0-28-generic #47-Ubuntu SMP '
                 b'Fri Jun 24 10:09:13 UTC 2016 x86_64')
     with patch('puresnmp.send') as mck:
         mck.return_value = data
         result = get('::1', 'private', '1.2.3')
     self.assertEqual(result, expected)
Пример #8
0
 def test_get(self):
     response = readbytes('apiv1/get_response.hex')
     self.transport.send.return_value = response
     result = snmp.get('192.168.1.1', 'private', '1.3.6.1.2.1.1.2.0')
     self.assertEqual(result, '1.3.6.1.4.1.8072.3.2.10')
     self.assertTrue(self.transport.send.called, 'method was not called')
     if six.PY3:
         self.assertIsInstance(result, str)
     else:
         self.assertIsInstance(result, unicode)
Пример #9
0
def fletcher2(oi, cou):
    while True:
        try:
            result = get(agip, com, oi, port=po)
            currtime = ti1()
            gloval[cou][oi] = result
            glotime[cou][oi] = currtime
            glorate[cou][oi] = result
            break
        except:
            fletcher2(oi, cou)
Пример #10
0
def fletcher2(oi,cou): 
               while True:
                 try: 
                   result = get(agip, com, oi, port=po)
                   print(result, end = " | ")
                   currtime=ti1()
                   
                   gloval[cou][oi]=result
                   glotime[cou][oi]=currtime
                   break
                 except:
                   fletcher2(oi,cou)                 
Пример #11
0
def fletcher(oi,cou): 
              while True:
               try: 
                   result = get(agip, com, oi, port=po)
                   value=result
                   ti4=ti1()                                #Time of recieving the value
                   currtime=ti4
                   
                   gloval[cou][oi]=result
                   glotime[cou][oi]=currtime
                   
                   glorate[cou][oi]=rate12(gloval[cou-1][oi],gloval[cou][oi],glotime[cou-1][oi],glotime[cou][oi]) #####The magic piece#####
                   print(glorate[cou][oi], end=" | ")
                   break
               except:
                   fletcher(oi,cou)               
Пример #12
0
    def walk_ip(self,
                address: tuple,
                settings_storage: BridgeSettings,
                first_try: bool = True) -> dict:
        ip, port = address
        is_success: bool = False
        other_family: str = ("public" if settings_storage.snmp_family
                             == "hytera" else "hytera")
        try:
            for oid in SNMP.ALL_KNOWN:
                raw_oid = oid.replace("iso", "1")
                snmp_result = get(
                    ip=ip,
                    community=settings_storage.snmp_family,
                    oid=raw_oid,
                    version=Version.V1,
                )
                if oid in SNMP.ALL_STRINGS:
                    snmp_result = octet_string_to_utf8(str(
                        snmp_result, "utf8"))
                elif oid in SNMP.ALL_FLOATS:
                    snmp_result = int.from_bytes(snmp_result, byteorder="big")
                settings_storage.hytera_snmp_data[oid] = snmp_result
            is_success = True
        except SystemError:
            self.log_error("SNMP failed to obtain repeater info")
        except Timeout:
            if first_try:
                self.log_debug(
                    "Failed with SNMP family %s, trying with %s as well" %
                    (settings_storage.snmp_family, other_family))
                settings_storage.snmp_family = other_family
                self.walk_ip(address=address,
                             settings_storage=settings_storage,
                             first_try=False)
            else:
                self.log_error(
                    "SNMP failed, maybe try changing setting.ini [snmp] family = %s"
                    % other_family)

        if is_success:
            self.print_snmp_data(settings_storage=settings_storage)

        return settings_storage.hytera_snmp_data
Пример #13
0
    def _poll_cycle(self):
        """
        This method gets called by scheduler and queries all oids defined in items
        """
        self.logger.debug("Query cycle called")

        for oid in self._items:
            if not self.alive:
                self.logger.debug("Self not alive".format(oid))
                break
            for prop in self._items[oid]:
                item = self._items[oid][prop]['item']

                host = self.host
                community = self.community
                oid = oid
                prop = prop
                self.logger.debug(
                    'Poll for item: {} with property: {} using oid: {}, host: {}, community: {} '
                    .format(item, prop, oid, host, community))

                # Request data
                try:
                    response = get(host, community, oid)
                    self.logger.debug(
                        'Successfully received response: {}'.format(response))
                except Exception as e:
                    self.logger.error(
                        'Exception occured when getting data of OID {}: {}'.
                        format(oid, e))
                    return

                # Transform response
                result = 0
                unit = 0

                try:
                    response = response.decode('ascii')
                except Exception as e:
                    response = response
                    self.logger.debug(
                        'Response for OID {} not decoded, since it was no ASCII string. Error was: {}'
                        .format(oid, e))
                else:
                    self.logger.debug('Response decoded')

                if prop == 'value':
                    # Prüfung, ob Leerzeichen vorhanden sind, um den Wert von Einheit zu trennen
                    try:
                        code_pos = response.index(" ")
                    except:
                        result = float(response)
                    else:
                        unit_short = (response[(code_pos + 1):(code_pos +
                                                               2)]).lower()
                        value = float(response[:(code_pos)])

                        if unit_short == 'c':
                            result = int(value)
                            unit = unit_short.upper()
                        elif unit_short == '%':
                            result = round(value / 100, 3)
                            unit = response[(code_pos + 1):len(response)]
                        elif unit_short == 'm' or unit_short == 'g' or unit_short == 't':
                            result = round(value, 3)
                            unit = response[(code_pos + 1):len(response)]
                        elif unit_short == 'r':
                            result = int(value)
                            unit = response[(code_pos + 1):len(response)]
                        else:
                            result = round(value, 3)
                            self.logger.debug(
                                'Response value typ not defined; using standard conversion to float'
                            )
                elif prop == 'string':
                    result = str(response)
                    unit = 'no'
                else:
                    self.logger.debug('Item property not defined in item.conf')

                # Set item value
                self.logger.debug(
                    'Response successfully transformed to: {} with unit: {} '.
                    format(result, unit))
                item(result, 'SNMP')
Пример #14
0
def fletcher2(oi):

    result = get(agip, com, oi, port=po)
    print(result, end=" | ")
Пример #15
0
def cisco_sg300(IP, COMMUNITY):
    from puresnmp import walk
    from puresnmp import get
    from puresnmp import table
    import pandas as pd
    oid_name = "1.3.6.1.4.1.9.9.23.1.3.4.0"
    oid_if = "1.3.6.1.4.1.9.9.23.1.1.1.1"
    oid_cdp = "1.3.6.1.4.1.9.9.23.1.2.1"
    oid_if_remote = "1.3.6.1.4.1.9.9.23.1.2.1.1.7"
    oid_ip_remote = "1.3.6.1.4.1.9.9.23.1.2.1.1.4"
    oid_name_remote = "1.3.6.1.4.1.9.9.23.1.2.1.1.6"
    oid_model_remote = "1.3.6.1.4.1.9.9.23.1.2.1.1.8"
    try:
        local_name = get(IP, COMMUNITY, oid_name)
        local_name = local_name.decode()
        interfaces = table(IP, COMMUNITY, oid_if)
        interfaces = interfaces[0]
        remote = []
        local_if = []
        for row in walk(IP, COMMUNITY, oid_name_remote):
            interface = str(row[0])
            interface = interface.split(".")
            port = interfaces[interface[14]]
            remote.append(row[1].decode())
            local_if.append(port.decode())
        df_result = pd.DataFrame({
            'local': local_name,
            'local_if': local_if,
            'remote': remote
        })
        ## interface remota
        result_remote_if = table(IP, COMMUNITY, oid_if_remote)
        result_remote_if = result_remote_if[0]
        del result_remote_if['0']
        remote_if = list(result_remote_if.values())
        remote_if = [i.decode() for i in remote_if]
        df_result['remote_if'] = remote_if
        ### ips remote
        ips = table(IP, COMMUNITY, oid_ip_remote)
        ips = ips[0]
        del ips['0']
        ips = list(ips.values())
        ips = [i.hex() for i in ips]
        ips = [iphex(i) for i in ips]
        df_result['remote_ip'] = ips
        ### remote model
        model_remote = table(IP, COMMUNITY, oid_model_remote)
        model_remote = model_remote[0]
        del model_remote['0']
        model_remote = list(model_remote.values())
        model_remote = [i.decode() for i in model_remote]
        df_result['remote_model'] = model_remote
        return df_result
    except:
        print("error : " + IP)
        column_names = [
            "local", "local_if", "remote", "remote_if", "remote_ip",
            "remote_model"
        ]
        df_result = pd.DataFrame(columns=column_names)
        return df_result
Пример #16
0
from puresnmp import get
from puresnmp.api.raw import get as raw_get

ip = "192.168.7.99"
community = "public"
oid = '1.3.6.1.2.1.3.1.1.3.0.1.192.168.7.99'  # only example

result = get(ip, community, oid)
raw_result = raw_get(ip, community, oid)

print(type(result), repr(result))
print(type(raw_result), repr(raw_result))
Пример #17
0
    def __process_methods(method, common_parameters, datatype_config):
        response = None

        if method == "get":
            oid = datatype_config["oid"]
            response = puresnmp.get(**common_parameters, oid=oid)
        elif method == "multiget":
            oids = datatype_config["oid"]
            oids = oids if isinstance(oids, list) else list(oids)
            response = puresnmp.multiget(**common_parameters, oids=oids)
        elif method == "getnext":
            oid = datatype_config["oid"]
            master_response = puresnmp.getnext(**common_parameters, oid=oid)
            response = {master_response.oid: master_response.value}
        elif method == "multigetnext":
            oids = datatype_config["oid"]
            oids = oids if isinstance(oids, list) else list(oids)
            master_response = puresnmp.multigetnext(**common_parameters,
                                                    oids=oids)
            response = {
                binded_var.oid: binded_var.value
                for binded_var in master_response
            }
        elif method == "walk":
            oid = datatype_config["oid"]
            response = {
                binded_var.oid: binded_var.value
                for binded_var in list(
                    puresnmp.walk(**common_parameters, oid=oid))
            }
        elif method == "multiwalk":
            oids = datatype_config["oid"]
            oids = oids if isinstance(oids, list) else list(oids)
            response = {
                binded_var.oid: binded_var.value
                for binded_var in list(
                    puresnmp.multiwalk(**common_parameters, oids=oids))
            }
        elif method == "set":
            oid = datatype_config["oid"]
            value = datatype_config["value"]
            response = puresnmp.set(**common_parameters, oid=oid, value=value)
        elif method == "multiset":
            mappings = datatype_config["mappings"]
            response = puresnmp.multiset(**common_parameters,
                                         mappings=mappings)
        elif method == "bulkget":
            scalar_oids = datatype_config.get("scalarOid", [])
            scalar_oids = scalar_oids if isinstance(
                scalar_oids, list) else list(scalar_oids)
            repeating_oids = datatype_config.get("repeatingOid", [])
            repeating_oids = repeating_oids if isinstance(
                repeating_oids, list) else list(repeating_oids)
            max_list_size = datatype_config.get("maxListSize", 1)
            response = puresnmp.bulkget(**common_parameters,
                                        scalar_oids=scalar_oids,
                                        repeating_oids=repeating_oids,
                                        max_list_size=max_list_size)._asdict()
        elif method == "bulkwalk":
            oids = datatype_config["oid"]
            oids = oids if isinstance(oids, list) else list(oids)
            bulk_size = datatype_config.get("bulkSize", 10)
            response = {
                binded_var.oid: binded_var.value
                for binded_var in list(
                    puresnmp.bulkwalk(
                        **common_parameters, bulk_size=bulk_size, oids=oids))
            }
        elif method == "table":
            oid = datatype_config["oid"]
            del common_parameters["timeout"]
            num_base_nodes = datatype_config.get("numBaseNodes", 0)
            response = puresnmp.table(**common_parameters,
                                      oid=oid,
                                      num_base_nodes=num_base_nodes)
        elif method == "bulktable":
            oid = datatype_config["oid"]
            num_base_nodes = datatype_config.get("numBaseNodes", 0)
            bulk_size = datatype_config.get("bulkSize", 10)
            response = puresnmp.bulktable(**common_parameters,
                                          oid=oid,
                                          num_base_nodes=num_base_nodes,
                                          bulk_size=bulk_size)
        else:
            log.error("Method \"%s\" - Not found", str(method))
        return response
Пример #18
0
TEMPLATE_DIR = '/opt/CM-RT-GRAPH/telegraf/rtPoller/templates/'
CMTS_JSON = 'cmts.json'
TELEGRAF_CONFIG_DIR = '/etc/telegraf/telegraf.d/'
CMTS_TEMPLATE = ("%stmp.cmts.conf" % (TEMPLATE_DIR))
CM_TEMPLATE = ("%stmp.cm.conf" % (TEMPLATE_DIR))

with open("%s%s" % (TEMPLATE_DIR, CMTS_JSON), 'r') as f:
    cmtses = json.load(f)

DECMAC = returnDecMAC(CMMAC)
PTR_OID = ("1.3.6.1.2.1.10.127.1.3.7.1.2.%s" % (DECMAC))

for cmts in cmtses:
    ptr = None
    try:
        ptr = get(cmts['hostname'], cmts['community'], PTR_OID, cmts['port'])
    except:
        print("No such OID on CMTS:", cmts['hostname'],
              "proceed to the next one!")
        continue

    if ptr is not None:
        CM_IP_OID = ("1.3.6.1.2.1.10.127.1.3.3.1.3.%s" % (ptr))
        CMIP = get(cmts['hostname'], cmts['community'], CM_IP_OID,
                   cmts['port'])
        CMIP = str(ipaddress.IPv4Address(CMIP))

        TMP_CM = open(CM_TEMPLATE, "r")
        CM_TELEGRAF_FILE = ("%stmp.cm.%s.conf" % (TELEGRAF_CONFIG_DIR, CMMAC))
        TELE_CM = open(CM_TELEGRAF_FILE, "w")
        for line in TMP_CM:
Пример #19
0
def snmp_get(oid):
    # Python 2 compatibility
    host = SNMP_CONFIG['host']
    if hasattr(host, 'decode'):
        host = host.decode('utf-8')
    return puresnmp.get(host, SNMP_CONFIG['community'], oid)