Пример #1
0
def connect_and_setup():
    for dev in config['denkovi']:
        dev['state'] = 0
        if 'sessionread' in dev and 'sessionwrite' in dev:
            print('Already connected to ' + dev['id'] + ', continuing')
            continue
        try:
            dev['sessionread'] = Session(hostname=dev['host'],
                                         remote_port=dev['port'],
                                         community=dev['communityread'],
                                         version=2)
            dev['sessionwrite'] = Session(hostname=dev['host'],
                                          remote_port=dev['port'],
                                          community=dev['communitywrite'],
                                          version=2)
        except:
            print('Error creating session, device not available?')
            continue
        for relay in dev['relays']:
            identifier = dev['id'] + '_relay_' + str(relay['number'])
            dtopic = config['mqtt']['discovery_prefix'] + '/light/' + \
                     identifier + '/config'
            topic = config['mqtt']['topic'] + '/light/' + identifier
            name = relay['name']

            payload = {
                "state_topic": topic + '/state',
                "command_topic": topic + '/set',
                "name": name,
                "unique_id": identifier,
                "device": {
                    "identifiers":
                    base64.b64encode(
                        dev['host'].encode('ascii')).decode('ascii'),
                    "manufacturer":
                    'Denkovi',
                    "name":
                    dev['name'],
                    "model":
                    "SmartDEN",
                },
            }

            #payload = ""
            payload = json.dumps(payload)
            mqttc.publish(dtopic, payload=payload, retain=True)
            mqttc.publish(topic + '/state', payload="OFF", retain=True)
            stopic = topic + "/set"
            if not stopic in subscriptions:
                subscriptions.append(stopic)
            mqttc.subscribe(stopic)
Пример #2
0
 def verificaSenha(self):
     usuario = self.nome.get()
     senha = self.senha.get()
     ip = self.ip.get()
     hash = self.hash.get()
     encryption = self.encryption.get()
     try:
         global session
         global numInterfaces
         session = Session(hostname=ip,
                           version=3,
                           security_level='auth_with_privacy',
                           security_username=usuario,
                           auth_protocol=hash,
                           auth_password=senha,
                           privacy_protocol=encryption,
                           privacy_password=senha)
         numInterfaces = int(session.get('ifNumber.0').value)
         self.mensagem["text"] = "Autenticado"
         t = threading.Thread(target=analyze_interfaces)
         t.start()
         ani = animation.FuncAnimation(fig, plot_chart, interval=1000)
         ani2 = animation.FuncAnimation(fig2, plot_chart2, interval=1000)
         ani3 = animation.FuncAnimation(fig3, plot_chart3, interval=1000)
         plt.show()
     except:
         print('Ocorreu um erro. Verifique o que aconteceu.')
         self.mensagem["text"] = "Falha durante autenticacao"
Пример #3
0
def get_usage_mem(chat_id, bot):
    """ Send response of 'snmpget' request for usage RAM.

    :param chat_id: chat id to send SNMP get response.
    :param bot: bot instance.
    """
    try:
        session = Session(hostname=host_details.get_host(),
                          community=host_details.get_community(),
                          version=host_details.get_version())

        mem_avail_real = session.get(".1.3.6.1.4.1.2021.4.6.0")
        mem_total_real = session.get(".1.3.6.1.4.1.2021.4.5.0")
        mem_usage = float(mem_total_real.value) - float(mem_avail_real.value)
        percentage = (100 * mem_usage) / float(mem_total_real.value)
        gb_usage = mem_usage / (1024 * 1024)

        bot.sendMessage(
            chat_id, 'RAM usage on: ' + host_details.get_host() + ' = ' +
            str(round(percentage, 2)) + "%" + " (" + str(round(gb_usage, 2)) +
            "GB)")
        bot.sendMessage(chat_id,
                        'Back to command list',
                        reply_markup=bot_command.keyboard)

    except exce.EasySNMPError as error:
        bot.sendMessage(
            chat_id, 'Error during processing the request, agent: <' +
            host_details.get_host() + ' ' + host_details.get_community() +
            '> on used mem request')
        bot_command.back_home(chat_id, bot)
        print(error)
Пример #4
0
def get_disk(chat_id, bot):
    """ Send response of 'snmpget' request for dskPercent (Disk usage percent)

    :param chat_id: chat id to send SNMP get response.
    :param bot: bot instance.
    """

    try:
        session = Session(hostname=host_details.get_host(),
                          community=host_details.get_community(),
                          version=host_details.get_version())

        disk = session.get(".1.3.6.1.4.1.2021.9.1.9.1")

        bot.sendMessage(
            chat_id, 'Actual Disk usage on: ' + host_details.get_host() +
            ' = ' + str(disk.value) + "%")
        bot.sendMessage(chat_id,
                        'Back to command list',
                        reply_markup=bot_command.keyboard)

    except exce.EasySNMPError as error:
        bot.sendMessage(
            chat_id, 'Error during processing the request, agent: <' +
            host_details.get_host() + ' ' + host_details.get_community() +
            '> on disk request')
        bot_command.back_home(chat_id, bot)
        print(error)
Пример #5
0
def query_interfaces_status():
    interface_dict = {}
    for id in config.SWITCHES:
        switch_name = config.SWITCHES[id]["name"]
        hostname = config.SWITCHES[id]["hostname"]
        username = config.SWITCHES[id]["username"]
        password = config.SWITCHES[id]["password"]

        session = Session(hostname=hostname,
                          security_level=u"auth_with_privacy",
                          security_username=username,
                          auth_protocol=u"SHA",
                          auth_password=password,
                          privacy_password=password,
                          version=3)

        interfaces_status = session.walk("1.3.6.1.2.1.2.2.1.8")

        for item in interfaces_status:
            search_text = "tag:" + switch_name + "_" + parse_interface_name(
                item.oid.replace("iso.3.6.1.2.1.2.2.1.8.", ""))
            result_line = ""
            with open(config.ALLOCATION) as file:
                for line in file:
                    line = line.rstrip()
                    if search_text in line:
                        result_line = line
                        break

            if result_line != "":
                port_ip_address = result_line.split(",")[1]
                interface_dict[port_ip_address] = item.value

    return interface_dict
Пример #6
0
def get_cpu_usage(chat_id, bot):
    """ Send response of 'snmpget' request for CPU usage.

    :param chat_id: chat id to send SNMP get response.
    :param bot: bot instance.
    """
    try:
        session = Session(hostname=host_details.get_host(),
                          community=host_details.get_community(),
                          version=host_details.get_version())

        cpuUsage = session.get(".1.3.6.1.4.1.2021.11.9.0")
        cpu = int(cpuUsage.value)

        bot.sendMessage(
            chat_id, 'Actual CPU percentage: ' + host_details.get_host() +
            ' = ' + str(cpu) + "%")
        bot.sendMessage(chat_id,
                        'Back to command list',
                        reply_markup=bot_command.keyboard)

    except exce.EasySNMPError as error:
        bot.sendMessage(
            chat_id,
            'Error during interrogation, agent: <' + host_details.get_host() +
            ' ' + host_details.get_community() + '> on cpu request')
        bot_command.back_home(chat_id, bot)
        print(error)
Пример #7
0
    def __init__(self, host, community="aspiringvision", version=2, rt=None):
        self.host = host
        self.community = community
        self.version = version
        self.session = Session(hostname=self.host, community=self.community, version=self.version)
        self.neighbors = []
        
        self.osiris_service_manifest = [
                { 'name': 'snmpd',       'desc': 'SNMP daemon.',                       'unis_name': 'snmp',       'unis_service_type': 'host:snmp'},
                { 'name': 'ryu-manager', 'desc': 'RYU SDN Controller.',                'unis_name': 'ryu',        'unis_service_type': 'nmal:tools:ryu'},
                { 'name': 'lldpd',       'desc': 'LLDP daemon.',                       'unis_name': 'lldp',       'unis_service_type': 'host:lldp'},
                { 'name': 'periscoped',  'desc': 'UNIS network resource database.',    'unis_name': 'periscope',  'unis_service_type': 'ps:tools:periscope'},
                { 'name': 'node',        'desc': 'NodeJS web application.',            'unis_name': 'nodejs',     'unis_service_type': 'host:node'},
                { 'name': 'blippd',      'desc': 'BLIPP performance monitoring tool.', 'unis_name': 'blipp',      'unis_service_type': 'ps:tools:blipp'},
                { 'name': 'ntpd',        'desc': 'Network Time Protocol Daemon',       'unis_name': 'ntp',        'unis_service_type': 'host:ntp'},
                { 'name': 'schedular',   'desc': 'PSchedular Service',                 'unis_name': 'pschedular', 'unis_service_type': 'ps:tools:pschedular'},
                { 'name': 'archiver',    'desc': 'PerfSONAR Esmond Archive utility',   'unis_name': 'esmond',     'unis_service_type': 'ps:tools:esmond'},
                { 'name': 'owampd',      'desc': 'OWAMP web server',                   'unis_name': 'owamp',      'unis_service_type': 'host:owamp'}]


        # TODO: make runtime element from config, hardcode placeholder for now
        if rt is None:
            self.rt = Runtime('http://172.18.0.25:9000')
        else:
            self.rt = rt
Пример #8
0
def getRoutingTable(ipRouter, router=None):
    session = Session(hostname=ipRouter, community=COMMUNITY,
                      version=2)  # crear sessio per connectar amb el router
    networks = session.walk('IP-FORWARD-MIB::ipCidrRouteDest')  # xarxes desti
    nexthop = session.walk(
        'IP-FORWARD-MIB::ipCidrRouteNextHop')  # nexthop per la xarxa desti
    tipus = session.walk('IP-FORWARD-MIB::ipCidrRouteType')  # tipus de ruta
    masks = session.walk(
        'IP-FORWARD-MIB::ipCidrRouteMask')  # mascara de la xarxa desti

    table = list()

    for x, y, z, n in zip(networks, masks, nexthop,
                          tipus):  # combinem linea a linea la informacio rebuda
        route = RouteEntry(x.value, y.value,
                           z.value)  # creem un objecte ruta a partir de la informacio anterior
        router.addRoute(route)  # afegim aquesta ruta al router
        tipus = ''  # descodifiquem el valor rebut a llenguatge huma
        if (n.value == '1'):
            tipus = 'Other'
        elif (n.value == '2'):
            tipus = 'Reject'
        elif (n.value == '3'):
            tipus = 'Local'
        elif (n.value == '4'):
            tipus = 'Remote'

        table.append((x.value, y.value, z.value,
                      tipus))  # afegim la informacio anterior a la taula a mostrar

    print 'RoutingTable: '
    headers = ["Network", "Mask", "Nexthop", "Type"]  # definim capcalera taula
    print tabulate(table, headers, tablefmt="fancy_grid")  # printar taula
 def __init__(self, snmp_host, community, version):
     self._snmp_host_ = snmp_host
     self._session_ = Session(hostname=snmp_host,
                              community=community,
                              version=version,
                              use_long_names=True,
                              use_sprint_value=True)
Пример #10
0
def get_interface_stats(task, interface_dict):
    f = open(f'{task.host.hostname}_interface_{interface_dict["ifslug"]}.txt',
             'a')
    # session = Session(hostname=task.host.hostname, community='private', version=2)
    session = Session(
        hostname=task.host.hostname,
        version=3,
        security_level='auth_with_privacy',
        security_username='******',
        auth_protocol='SHA',
        auth_password='******',
        privacy_password='******',
        privacy_protocol='AES',
    )
    in_octets = session.get(
        f'.1.3.6.1.2.1.2.2.1.10.{interface_dict["ifindex"]}')
    out_octets = session.get(
        f'.1.3.6.1.2.1.2.2.1.16.{interface_dict["ifindex"]}')
    print(in_octets,
          out_octets)  #Printing data just to make sure that it's running...
    f.write(
        f'{datetime.now().isoformat()},{interface_dict["ifname"]},{in_octets.value},{out_octets.value}\n'
    )
    f.close()
    return [in_octets, out_octets]
Пример #11
0
def thread_bulk_TotalBytes(oid,results,index):
    session = Session(hostname=args.ip_address, community=args.community, version=2, use_numeric=True)
    try:
        print("Bulk walk Starting...."+oid)
        results[index] = session.bulkwalk(oid,non_repeaters=0,max_repetitions=snmp_max_repetitions)
    except:
        print("Bulk walk Failed, oid: "+oid)
Пример #12
0
 def handle(self, *args: Any, **options: Any):
     devs = (Device.objects.exclude(
         ip_address=None,
         man_passw=None,
     ).filter(dev_type__in=[1, 9, 10]).iterator())
     for dev in devs:
         try:
             print("Try to scan", str(dev))
             ses = Session(str(dev.ip_address), 2,
                           str(dev.man_passw or "public"))
             sys_name = ses.get(".1.3.6.1.2.1.1.1.0").value
             if not sys_name or sys_name == "NOSUCHINSTANCE":
                 continue
             if "DGS-1100-10" in sys_name:
                 dev.dev_type = 1
             elif "DGS-1100-06" in sys_name:
                 dev.dev_type = 10
             elif "DGS-3120-24SC" in sys_name:
                 dev.dev_type = 9
             else:
                 continue
             print("\tSet dev type to:", sys_name)
             dev.save(update_fields=["dev_type"])
         except (EasySNMPError, SystemError) as err:
             print(str(dev), "ERROR:", err)
Пример #13
0
def main():

    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("-H", "--hostname", help="IP Address / Hostname to check [REQUIRED]",type=str, required=True)
    parser.add_argument("-c", "--community",help="SNMP Community (default 'public')",type=str,default='public')

    args = parser.parse_args()
    hostname = args.hostname
    comm = args.community
    
    session = Session(hostname=hostname, community=comm, version=2)
    try:
        item = session.walk(ifName)
    except:
        sys.exit('\nSNMP PROBLEM host '+hostname+" check IP and COMMUNITY\n")
    # get uptime to calculate last change
    uptime = session.get(sysUpTime).value
    print '\nHOST\t'+hostname
    print "\nUPTIME\t"+str(timedelta(seconds=(int(uptime)/100)))+"\n"
    # port names to include or ignore to filter useless values
    include= ('ethernet')
    ignore = ('Vl','vlan','VLAN','VLAN-','Trk','lo','oobm','Po','Nu','Gi/--Uncontrolled','Gi/--Controlled','Te/--Uncontrolled','Te/--Controlled')
    for value in item:
        # remove all digits from port names before filtering
        result = ''.join(i for i in value.value if not i.isdigit())
        if (result in include) or (result not in ignore):
            ifname = value.value
            # id defines the interface, will be appended to following snmp get
            id = value.oid_index
            #descr = session.get(ifAlias+id)
            opstatus = ifstatus[session.get(ifOperStatus+'.'+id).value]
            lastchangedate = lastchange2date(uptime,session.get(ifLastChange+'.'+id).value)
            print str(ifname)+"\tSTATUS "+opstatus+"\tLAST CHANGE SINCE DAYS\t"+lastchangedate
Пример #14
0
def discover(subnet):
    """
    Function that discovers the devices in the subnet
    by doing SNMP get on the system description OID.
    Subnet obtained from system argument

    :param subnet: IPNetwork object
    :return: None

    """
    global file_open
    global next_ip

    # Running through al the hosts in the subnet
    for ip in subnet:
        if next_ip and ip < next_ip:
            continue

        session = Session(hostname=ip.exploded,
                          community=sys.argv[2],
                          version=2,
                          retries=1)
        try:
            sysdescription = session.get('1.3.6.1.2.1.1.1.0')
            if re.search('JUNOS ([^ ]+)', sysdescription.value):
                logging.info("Found Juniper at %s" % (ip.exploded, ))
                with open(sys.argv[3], 'a') as f:
                    f.write(ip.exploded + ':juniper:up\n')
            else:
                logging.info("Skipping %s: Not Junos" % (ip.exploded, ))
        except Exception as e:
            logging.info('Skipping: %s: %s' % (ip.exploded, str(e)))
Пример #15
0
    def get_memory_snmp(self):
        session = Session(hostname=str(self.device["ip_mgmt"]),
                          community=self.device["snmp"]["community"],
                          version=self.device["snmp"]["version"])
        try:
            mem_util_used = session.get(
                invent.get_oid("mem_util_used", self.device["vendor"])).value
            mem_util_used = int(mem_util_used)
            if self.device["vendor"] == "Cisco":
                mem_util_free = session.get(
                    invent.get_oid("mem_util_free",
                                   self.device["vendor"])).value
                mem_util_used = (mem_util_used * 100) / (mem_util_used +
                                                         int(mem_util_free))
                mem_util_free = 100 - mem_util_used
            elif self.device["vendor"] == "Juniper":
                mem_util_free = 100 - mem_util_used
            self.logger.info(
                "Finished collecting Memory utilization for device {:s}".
                format(self.device["ip_mgmt"]))
        except:
            mem_util_used = None
            mem_util_free = None
            self.logger.warning(
                "Error collecting Memory utilization for device {:s}".format(
                    self.device["ip_mgmt"]))

        # TODO: tobe delete, only for demo
        import random
        mem_util_used = random.randint(10, 50)
        mem_util_free = 100 - mem_util_used
        return mem_util_used, mem_util_free
def determine_printer_model(hostname, version):
    """ Get the printer's model name from the SNMP data.

    The function tries to get the printer's model name through the SNMP data.
    It can sometimes raise a SystemError exception but I have seen it be multiple
      different errors so it returns -2 indicating that it is an unexpected error.
    If the model name is actually a string of 'NOSUCHINSTANCE', that means that the
      printer is too old and/or it needs a firmware update to have all the SNMP access.

    Args:
        hostname (str):
        version (int):
    
    Returns:
        printer_model_name (str): A string with the printer's models name retrieved
            from SNMP.
        Negative int: -2 = unspecified error.
                      -3 = SNMP data not given (printer/firmware too old).
    """
    session = Session(hostname=hostname, community='public', version=version)

    try:
        printer_model_name = session.get('.1.3.6.1.2.1.25.3.2.1.3.1').value
    except SystemError:
        return -2

    # If the SNMP data gives 'NOSUCHINSTANCE' that means that the firmware of
    #   the printer needs to be updated or the printer is too old.
    if str(printer_model_name) == "NOSUCHINSTANCE":
        return -3

    return printer_model_name
Пример #17
0
def estatusInterfaces(hostname, community, version, num):
    session = Session(hostname=hostname, community=community, version=version)
    try:
        description = str(session.get('1.3.6.1.2.1.2.2.1.8.' + str(num)))
    except EasySNMPTimeoutError:
        description = 'Timeout Error'
    return obtenerSubcadena(description)
Пример #18
0
 def __init__(self, hostname, community, version):
     # self.temp = [temp_sysDesc, temp_hostname, temp_totalInt, temp_MemUse, temp_MemFree, temp_NvramSize, temp_NvramUse, temp_Power, temp_Vol, temp_Location]
     self.hostname = hostname
     self.community = community
     self.version = version
     self.session = Session(hostname=self.hostname,
                            community=self.community, version=self.version)
Пример #19
0
def f5_engine_monit_cpu(snmp_ip, snmp_comm, splunk_host, splunk_key,
                        splunk_url, default_info):
    print(snmp_ip + ' : INICIO CPU')
    session = Session(hostname=snmp_ip,
                      community=snmp_comm,
                      version=2,
                      timeout=5,
                      retries=0)
    spk_session = requests.Session()

    ## CPU - LEITURA DAS OID
    print(snmp_ip + ' : LER CPU')
    sysMultiHostCpuUsageRatio5m = session.bulkwalk(
        'F5-BIGIP-SYSTEM-MIB::sysMultiHostCpuUsageRatio5m')

    ## CPU - PREENCHIMENTO DO JSON
    data = json_default_info(default_info)
    for index, f5_cpu in enumerate(sysMultiHostCpuUsageRatio5m):
        data['sysMultiHostCpuUsageRatio5m_' + str(index)] = f5_cpu.value

    ## CPU - EXPORTACAO DOS DADOS PARA O SPLUNK HEC
    print(snmp_ip + ' : SPLUNK CPU')
    event_data = '{"host":"' + splunk_host + '","source":"f5_cpu_stats","event":' + json.dumps(
        data) + '}'
    send_to_splunk(spk_session, event_data)
Пример #20
0
def potencia(olt, comnty, pon=None, tipo='onu'):
    """ Retorna o sinal rx de cada onu na pon passada.""" # Saída é meiia estranha :/ ex: ['HWTC\x84½\x00\x9a', 'HWTC¶\x9eD\x9c']
    sinais_snmp = []
    try: # Tentando criar a sessão snmp
        session = Session(hostname=olt, community=comnty, version=2)
    except: # algum parâmetro errado
        print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}")
        sys.exit()
    try: # Tentando realizar o snmpwalk
        if pon: # pon específica
            if tipo == 'onu':
                sinais_snmp = session.walk(f'1.3.6.1.4.1.2011.6.128.1.1.2.51.1.4.{pon}') # oid que retorna Potência RX das ONUs
            elif tipo == 'olt':
                sinais_snmp = session.walk(f'.1.3.6.1.4.1.2011.6.128.1.1.2.51.1.6.{pon}') # oid que retorna Potência TX das ONUs
            else:
                print(f'Para consutar a potência, escolha apenas "onu" ou "olt". Você escolheu: {tipo}')
        else: # olt inteira
            if tipo == 'onu':
                sinais_snmp = session.walk('1.3.6.1.4.1.2011.6.128.1.1.2.51.1.4') # oid que retorna Potência RX das ONUs
            elif tipo == 'olt':
                sinais_snmp = session.walk('.1.3.6.1.4.1.2011.6.128.1.1.2.51.1.6') # oid que retorna Potência TX das ONUs
            else:
                print(f'Para consutar a potência, escolha apenas "onu" ou "olt". Você escolheu: {tipo}')
    except: # timeout
        print("Não foi possível realizar o snmp walk das potências. Aguarde alguns instantes e tente novamente. Saindo...")
        sys.exit()
    sinais = []
    for sinal in sinais_snmp:
        temp = f'{int(sinal.value) / 100:.2f}' 
        sinais.append(str(temp))
    return sinais
Пример #21
0
    def fetchTable(self):
        session = Session(hostname=SNMP2JSON.args.hostname + ':' + SNMP2JSON.args.port, community=SNMP2JSON.args.community, version=SNMP2JSON.args.version)
        system_items = session.walk(SNMP2JSON.args.table)

        data = []
        for item in system_items:
            oid = item.oid
            oid_index = item.oid_index
            snmp_type = item.snmp_type
            value = item.value

            test = {
                'oid': oid,
                'oid_index': oid_index,
                'snmp_type': snmp_type,
                'value': value
            }

            data.append(test)

        allData = {
            '' + SNMP2JSON.args.table: data
        }

        if(SNMP2JSON.args.filename == None):
            print json.dumps(allData, indent=4, sort_keys=True)
        else:
            with open(SNMP2JSON.args.filename, 'wt') as f:
                f.write(json.dumps(allData, indent=4, sort_keys=True))
            print 'JSON Flushed to ' + SNMP2JSON.args.filename
Пример #22
0
def last_down_cause(olt, comnty, pon=None):
    """ Retorna o motivo da última queda de cada onu da pon passada. """
    try: # Tentando criar a sessão snmp
        session = Session(hostname=olt, community=comnty, version=2)
    except: # algum parâmetro errado
        print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}")
        sys.exit()
    try: # Tentando realizar o snmpwalk
        if pon: # pon específica
            resultado = session.walk(f'1.3.6.1.4.1.2011.6.128.1.1.2.46.1.24.{pon}') # oid que retorna descrições
        else: # olt inteira
            resultado = session.walk('1.3.6.1.4.1.2011.6.128.1.1.2.46.1.24') # oid que retorna descrições
    except: # timeout
        print("Não foi possível realizar o snmp walk do last down cause. Aguarde alguns instantes e tente novamente. Saindo...")
        sys.exit()
    resultados_value = []
    for res in resultado:
        if res.value == '2':
            resultados_value.append("___LOS___")
        elif res.value == '13':
            resultados_value.append("dying-gasp")
        elif res.value == '-1':
            resultados_value.append("info_zerada")
        else:
            resultados_value.append("cond_estranha")
    return resultados_value                 # retorna uma lista com as descrições
Пример #23
0
def main():
    opts = parseArgs()
    pyt = pytricia.PyTricia()
    pyt.insert('0.0.0.0/0', "root")
    pyt.insert('10.0.0.0/8', "RFC1918 root")
    pyt.insert('172.12.0.0/12', "RFC1918 root")
    pyt.insert('192.168.0.0/16', "RFC1918 root")

    prefx = {}
    IGNORED_INTERFACE = ['bme0', 'bme0.32768', 'lo']

    for device in opts['hosts']:
        try:
            session = Session(hostname=device,
                              community=opts['community'],
                              version=2)
            ipent = session.walk('IP-MIB::ipAdEntAddr')
            for item in ipent:
                ip = item.value
                ifIndex = session.get('IP-MIB::ipAdEntIfIndex.' + ip)
                mask = session.get('IP-MIB::ipAdEntNetMask.' + ip)
                ifName = session.get('IF-MIB::ifName.' + ifIndex.value)
                if ifName in IGNORED_INTERFACE:
                    print("Skipping %s" % ifName)
                    continue
                prefix = ip + "/" + str(
                    IPNetwork('0.0.0.0/' + mask.value).prefixlen)
                pref = IPNetwork(prefix)
                pyt.insert(str(prefix), device + "_" + ifName.value)
        except Exception, err:
            print("\tTIMEOUT: " + fw)
            print("\t" + str(err))
            continue
Пример #24
0
def make_telnet_connection():
    host = input("Ingresa la dirección del servidor TELNET: ")
    user = input("Ingresa el usuario: ")
    password = input("Ingresa la contraseña: ")

    start_time = int(time.time())
    try:
        tn = telnetlib.Telnet(host)
        tn.read_until(b"User: "******"\n")
        if password:
            tn.read_until(b"Password: "******"\n")

        tn.interact()

        print(tn.read_all().decode('ascii'))
    except Exception as e:
        print(e)

    final_time = int(time.time())
    print("\nTiempo de interacción: " + str(final_time - start_time))

    session = Session(hostname='localhost',
                      community="MacCommunity",
                      version=2)
    trafico_recibido = session.walk('1.3.6.1.2.1.2.2.1.10')
    trafico_enviado = session.walk('1.3.6.1.2.1.2.2.1.16')
    print("Trafico recibido: " + str(trafico_recibido))
    print("Trafico enviado: " + str(trafico_enviado))
Пример #25
0
def get_tasks(chat_id, bot):
    """ Send number of tasks in execution on host

    :param chat_id: chat id to send response.
    :param bot: bot instance.
    """
    try:
        session = Session(hostname=host_details.get_host(),
                          community=host_details.get_community(),
                          version=host_details.get_version())

        numTasks = session.get(".1.3.6.1.2.1.25.1.6.0")
        num = int(numTasks.value)

        bot.sendMessage(
            chat_id, 'Actual tasks in execution on: ' +
            host_details.get_host() + ' = ' + str(num))
        bot.sendMessage(chat_id,
                        'Back to command list',
                        reply_markup=bot_command.keyboard)

    except exce.EasySNMPError as error:
        bot.sendMessage(
            chat_id, 'Error during processing the request, agent: <' +
            host_details.get_host() + ' ' + host_details.get_community() +
            '> on num tasks request')
        bot_command.back_home(chat_id, bot)
        print(error)
Пример #26
0
def click_entrar():
    endereco = textentryEndereco.get()
    usuario = textentryUsuario.get()
    senha = textentrySenha.get()

    try:
	    global session
	    #session = Session(hostname=endereco, community='public', version=2, use_sprint_value = True)
	    session = Session(hostname=endereco, version=3, security_level="auth_with_privacy", security_username=usuario, auth_protocol=str(tipoAuth.get()), auth_password=senha,privacy_protocol=str(tipoCript.get()), privacy_password=senha, use_sprint_value = True)

            print(str(tipoAuth.get()))
            print(str(tipoCript.get()))

    	    textEndereco.insert(END, endereco)
            textEndereco.config(state=DISABLED)

	    name = session.get('sysName.0').value
	    textName.insert(END, name)
            textName.config(state=DISABLED)

            updateTime()

	    updateBytes()

            checkSites()

	    labelErro.config(text="")
	    textentryEndereco.delete(0, END)
	    textentryUsuario.delete(0, END)
	    textentrySenha.delete(0, END)
	    windowPrincipal.tkraise()

    except:
	labelErro.config(text="Não foi possível abrir a sessão!")
Пример #27
0
def get_tot_mem(chat_id, bot):
    """ Send response of 'snmpget' request for memTotalReal (Total RAM)

    :param chat_id: chat id to send SNMP get response.
    :param bot: bot instance.
    """
    try:
        session = Session(hostname=host_details.get_host(),
                          community=host_details.get_community(),
                          version=host_details.get_version())

        memTotalReal = session.get(".1.3.6.1.4.1.2021.4.5.0")
        mem = int(memTotalReal.value)

        bot.sendMessage(
            chat_id, 'Total RAM memory of the host: ' +
            host_details.get_host() + ' = ' + str(mem) + "kB")
        bot.sendMessage(chat_id,
                        'Back to command list',
                        reply_markup=bot_command.keyboard)

    except exce.EasySNMPError as error:
        bot.sendMessage(
            chat_id, 'Error during processing the request, agent: <' +
            host_details.get_host() + ' ' + host_details.get_community() +
            '> on tot mem request')
        bot_command.back_home(chat_id, bot)
        print(error)
def snmpConnection(version, community, hostname):
    try:
        session = Session(hostname=hostname,
                          community=community,
                          version=version)
        print(session)
    except EasySNMPConnectionError:
        print("ERROR: Invalid hostname or community.")
        exit(1)

    try:
        info = session.get('iso.3.6.1.2.1.1.5.0')
        print("\nName: ", info.value)
        info = session.get('iso.3.6.1.2.1.1.6.0')
        print("Location: ", info.value)
        info = session.get('iso.3.6.1.2.1.1.1.0')
        print("Description: ", info.value)
        info = session.get('iso.3.6.1.2.1.1.2.0')
        print("ID: ", info.value)
        info = session.get('iso.3.6.1.2.1.1.4.0')
        print("Contact: ", info.value)
    except:
        print("\nSystem info aren't available")

    return session
Пример #29
0
def get_power():
    session = Session(hostname=pdu_ip, community='perccom', version=2)
    sum = 0
    for i in range(1,9):
        snmp_response = session.get('1.3.6.1.4.1.13742.6.5.4.3.1.4.1.' + str(i) + ".5")
        sum += int(snmp_response.value)
    return sum
 def intstat(ip):
     ip_stat = {}
     list1 = []
     list2 = []
     dict_intf = {'1': 'fa0/0', '2': 'fa1/0', '3': 'fa1/1', '4': 'fa0/1'}
     dict_status = {'1': 'up', '2': 'down'}
     sess = Session(hostname=ip, community='public', version=2)
     sys = sess.walk(oids=u'.1.3.6.1.2.1.2.2.1.8')
     count = 0
     for item in sys:
         int1 = '{oid}.{oid_index} {snmp_type} = {value}'.format(
             oid=item.oid,
             oid_index=item.oid_index,
             snmp_type=item.snmp_type,
             value=item.value)
         add3 = re.split(r'\s', int1)
         add4 = add3[0].split('.')
         list1.append(add4[-1])
         list2.append(add3[-1])
         count += 1
     for i in range(0, count):
         int_name = dict_intf[list1[i]]
         int_stat = dict_status[list2[i]]
         ip_stat[int_name] = int_stat
     return ip_stat