def _session(self): """Create an SNMP session for queries. Args: None Returns: session: SNMP session """ # Create session if self._snmp_version != 3: session = easysnmp.Session(community=self._snmp_community, hostname=self._snmp_ip_target, version=self._snmp_version, remote_port=self._snmp_port, use_numeric=True, context=self._context_name) else: session = easysnmp.Session( hostname=self._snmp_ip_target, version=self._snmp_version, remote_port=self._snmp_port, use_numeric=True, context=self._context_name, security_level=self._security_level(), security_username=self._snmp_secname, privacy_protocol=self._priv_protocol(), privacy_password=self._snmp_privpassword, auth_protocol=self._auth_protocol(), auth_password=self._snmp_authpassword) # Return return session
def get_man_ip_add(ip): try: session = easysnmp.Session(hostname=ip, version=2, community=com) res = session.walk('.1.3.6.1.2.1.4.20.1.2') res1 = None for item in res: if item.value == man_vlan: res1 = item.oid_index break if res1 == None: for item in res: if item.value == str(int(float(man_vlan)) + 329): res1 = item.oid_index break if res1 == None: for item in res: if item.value == "34": res1 = item.oid_index break return res1 except Exception as e: print 'Something wrong on ip = ' + ip print(e) ans = 'failed' return ans
def get_data(hostname, community, interval, data_dict, stop_event): """Retrieve data from devices using SNMP""" try: #Create SNMP session session = easysnmp.Session(hostname=hostname, community=community, version=2) #Work until stop event is set while not stop_event.is_set(): #Send SNMP GETNEXT requests for tags for index, tag in enumerate(data_dict["tags"]): data_dict["tags"][index]["value"] = session.get_next( tag["oid"]).value #Send SNMP GETNEXT requests for fields for index, field in enumerate(data_dict["fields"]): data_dict["fields"][index]["value"] = int( session.get_next(field["oid"]).value) #Call function to write retrieved data to database write_to_db(data_dict) #Stop execution for predefined period of time (interval) time.sleep(interval) except easysnmp.EasySNMPTimeoutError: #Catch exception if there are some problem with SNMP connection to devices print Fore.RED + Style.BRIGHT + "**[SNMP] - Connection is timed out to the device! Please check SNMP configuration on your devices!" print "The program will be stopped!" print Fore.RED + Style.BRIGHT + "\n" sys.exit()
def get_infs_bySnmp(ip): def _get_infs(oid): index = oid.value desc = 'None' name = session.get(('ifDescr', index)).value if ' ' in name: name, desc = name.split(' ', 1) state = session.get(('ifOperStatus', index)).value if state == '1': state = 'up' else: state = 'down' bw = int(session.get(('ifSpeed', index)).value or 0) collTime = time.time() inCount = int(session.get(('ifInOctets', index)).value or 0) outCount = int(session.get(('ifOutOctets', index)).value or 0) return dict(name=name, desc=desc, state=state, bw=bw, inCount=inCount, outCount=outCount, collTime=collTime) try: session = easysnmp.Session(hostname=ip, community=community_read, version=1) indexs = session.walk('ifIndex') rslt = lmap(_get_infs, indexs) return ('success', rslt, ip) except (easysnmp.EasySNMPTimeoutError) as e: return ('fail', None, ip)
def get_ip_add(ip): # Pasiima kaimyu adresus is irenginio. session = easysnmp.Session(hostname=ip, version=2, community=com) try: res = session.walk('.1.0.8802.1.1.2.1.4.2.1.3') ans = [] temp1 = [] for item in res: temp1.append(item.oid) c = 0 for item in temp1: ans.append('') a = 0 b = 1 while a < 4: if (item[len(item) - b] == '.'): ans[c] = item[len(item) - b] + ans[c] a = a + 1 b = b + 1 else: ans[c] = item[len(item) - b] + ans[c] b = b + 1 ans[c] = ans[c].lstrip('.') c = c + 1 return ans except Exception as e: print 'Something wrong on ip = ' + ip print(e) ans = [] ans.append('failed') return ans
def get_port_macs(ip): session = easysnmp.Session(hostname=ip, version=2, community=com, use_sprint_value=True) res = session.walk('.1.3.6.1.2.1.2.2.1.6') ans = [] for item in res: ans.append(item.value) return ans
def update_model(): # clear_log() nodes = graph.cypher.execute("match (s:Switch) return s.ip as ip") switchs = [x['ip'] for x in nodes] for x in switchs: mark = 'success' try: session = easysnmp.Session(hostname=x, community=community, version=1) rslt = session.get('1.3.6.1.2.1.1.1.0').value model = re_find(r'((?<=Quidway )S\d+|(?<=ZXR10 )\w+(?= Software))', rslt) # model = re_find(r'(?:Quidway (S\d+)|ZXR10 (\w+) Software)', rslt) # model = select(bool, model)[0] if model.startswith('8905'): model = 'S' + model hostname = session.get('1.3.6.1.2.1.1.5.0').value except (easysnmp.EasySNMPTimeoutError) as e: mark = 'fail' graph.cypher.execute( "match (s:Switch) where s.ip={ip} set s.snmpState='abnormal'", ip=x) if mark == 'success': graph.cypher.execute( "match (s:Switch) where s.ip={ip} set s.model={model},s.hostname={hostname},s.snmpState='normal'", ip=x, model=model, hostname=hostname)
def update_dynamic_snmp_ports_qfx(host): ticks = time.time() if host not in gDynamicSNMPIndex or ticks - gDynamicSNMPIndex[host][ 'ticks'] > dyn_port_idx_update_interval: ports = {} session = easysnmp.Session(hostname=host, community=users['journal']['1'], version=2, retries=snmp_retries, use_numeric=True, timeout=snmp_timeout) try: # Выполняем опрос параметров из default_info snmp_response = session.walk('.1.3.6.1.2.1.31.1.1.1.1') except EasySNMPTimeoutError as err: logging.exception(err) pass else: for x in snmp_response: match = re.search('(([gx]e)|(et))\-0\/0\/([0-9]+)$', x.value) if match: ports[x.oid_index] = match.group(4) gDynamicSNMPIndex[host] = {'ticks': ticks, 'ports': ports} logging.debug(gDynamicSNMPIndex) else: logging.debug('cached') return
def __init__(self, hostname, user_name, auth_key, priv_key): self._session = easysnmp.Session( hostname=hostname, version=3, security_level="auth_with_privacy", security_username=user_name, auth_password=auth_key, auth_protocol="MD5", privacy_password=priv_key, privacy_protocol="AES128")
def check(default_oid, mem_crit="", mem_warn=""): ph = pynag.Plugins.PluginHelper() og_snmp = ph.parser.add_option_group("SNMP") og_snmp.add_option("-H", "--host", help="Hostname or ip address", dest="host", default="localhost") og_snmp.add_option("--oid", help="oid root for VM data", dest="oid", default=default_oid) og_snmp.add_option("-C", "--community", dest="community", default="public") og_snmp.add_option("-V", "--version", dest="version", default=2) og_cpu = ph.parser.add_option_group("CPU") og_cpu.add_option("--cpu-crit", help="vm cpu load in %", dest='cpu_c', default="") og_cpu.add_option("--cpu-warn", dest='cpu_w', default="") og_cpu.add_option("--cpu-dt-crit", help="uptime interval over which cpu was calculated", dest='dt_c', default="") og_cpu.add_option("--cpu-dt-warn", dest='dt_w', default="") og_mem = ph.parser.add_option_group("Memory") og_mem.add_option("--mem-crit", help="used memory in %", dest='mem_c', default=mem_crit) og_mem.add_option("--mem-warn", dest='mem_w', default=mem_warn) og_mem.add_option("--mem-b-crit", help="used memory in bytes", dest='b_c', default='') og_mem.add_option("--mem-b-warn", dest='b_w', default='') ph.parse_arguments() session = easysnmp.Session(hostname=ph.options.host, community=ph.options.community, version=int(ph.options.version)) add_cpu(ph, walk_cpu(session, ph.options.oid)) add_mem(ph, walk_mem(session, ph.options.oid)) add_host_cpu(ph, *get_host_cpu(session, ph.options.oid)) add_host_mem(ph, *get_host_mem(session, ph.options.oid)) ph.add_metric('timestamp', session.get("{oid}.0.0.0".format(oid=ph.options.oid)).value) ph.check_all_metrics() ph.exit()
def get_id_port(ip): # Pasiima kaimynu sasaju numerius session = easysnmp.Session(hostname=ip, version=2, community=com) try: res = session.walk('.1.0.8802.1.1.2.1.4.1.1.7') ans = [] for item in res: ans.append(item.value) return ans except Exception as e: ans = [] ans.append('') return ans
def process_device(device_module, request_params, json_resp, target_ip, snmp_comm, model, request): # Пробуем получить из модуля множитель 'timeout_mf' и применить его. При неудаче # будет использован таймаут из файла конфигурации сервиса current_snmp_timeout = int(swconfig.snmp_timeout * getattr(device_module, 'timeout_mf', 1)) # request_params - все, что содержится в ключе 'data' из запроса ('request'). Представлен в виде списка. # request_param - конкретный элемент списка, содержащий параметры конкретного запроса. Представлен в # виде словаря. В debug-лог пишется как 'URL Params'. # "data": [{"1": "2", "0": "swL2PortCtrlAdminState"}, {"0": ""}] # dataset - словарь вида {'Metric':'OID'}, список списков вида [['tag', 'iid', 'value', 'type']] или # кортеж со словарем внутри ({'2':'enable'},) из файла с таким же именем, как имя модели устройства (model) for request_param in request_params: try: method_name = request_param[0] except KeyError: continue # Пробуем извлечь параметр (метод) из файла модуля try: dataset = getattr(device_module, method_name) except AttributeError: if method_name == 'list': json_resp['data']['list'] = [ str(d) for d in dir(device_module) if d[0] != '_' ] else: logging.error( f"Can't find param '{method_name}' from module '{model}'!") json_resp['data'][method_name] = False else: # Для режима отладки пишем в лог кто и что у нас запросил if swconfig.debug_mode: client_host, client_port = request.transport.get_extra_info( 'peername') logging.debug( f"Request from {client_host}:{client_port}." f"Dataset: {str(dataset)}, URL Params: {str(request_param)}" ) current_snmp_retries = swconfig.snmp_retries # Если параметр находится в списке 'no_retries', сбрасываем для него число дополнительных попыток в 0 if method_name in swconfig.no_retries: current_snmp_retries = 0 # Создаем SNMP-сессию session = easysnmp.Session(hostname=target_ip, community=snmp_comm, version=2, retries=current_snmp_retries, use_numeric=True, timeout=current_snmp_timeout) # dataset может быть как словарем (для get/walk) так и списком (для set) и # кортежем (для неизменяемых пользовательских данных). Обрабатываем эти случаи отдельно if isinstance(dataset, dict): # Получаем функцию-хелпер и удаляем этот элемент, чтобы не мешался helper = None data_for_helper = {} try: helper_name = dataset.get('helper') del (dataset['helper']) helper = getattr(helpers, helper_name) logging.debug(f"Found {helper_name} helper function.") except KeyError: pass except AttributeError: logging.error(f"Can't find {helper_name} helper function.") # если хотя бы в одном названии параметра будет присутствовать точка, то выполняется GET-запрос get_notwalk = False for paramname in dataset: if '.' in paramname: get_notwalk = True break snmp_oids_list = [ prepare_oid(request_param.copy(), dataset[paramname], model, target_ip) for paramname in dataset ] # выполняем SNMP-опрос snmp_method = session.get if get_notwalk else session.walk snmp_result = snmp_method(snmp_oids_list) for var in snmp_result: # Убеждаемся, что ответ распознан, т.е. не None if var.oid_index is not None: # Получаем полный OID. full_oid = f"{var.oid}.{var.oid_index}" # Здесь k - имя параметра, по которому получим значение, а prep_k - имя ключа в 'data'. В # случае walk-запроса значения k и prep_k равны, а в случае get имя prep_k обрезается до первой # точки, не включая ее for k in dataset: # Если используем метод get, то получаем имя ключа из параметра k с начала до первой # точки, не включая ее, и задаем трейлер # Для метода опроса walk имя ключа будет равно параметру k, а трейлер должен быть пустым if get_notwalk: prep_k = k[0:k.find('.')] trailer = '*' else: prep_k = k trailer = '.' # Значение trailer прибавляем для избежания ложного срабатывания при сравнении OID, # например ...1.2.3.2 и ....1.2.3.20 # При Get-запросе full_oid всегда является "конечным", поскольку это "прицельный" # запрос. Поэтому здесь используем "жесткий" трейлер = '*' # Теперь будут сравниваться .1.2.3.2* и .1.2.3.20*. # Первое значение уже не входит во второе, как было бы в предыдущем случае # При Walk-запросе full_oid заранее неизвестен, поэтому используем "мягкий" трейлер = # '.' (символ точки является частью OID) # Также при Walk-запросе у нас есть отдельное требование - ветки должны быть одной длины # Если оно выполнено, значит сравниваемые ветки разные и точку использовать допустимо. # Ниже пример tmp_oid, которые "пересеклись" бы без трейлера # full_oid: .1.3.6.1.2.1.31.1.1.1.18.1 # tmp_oid: .1.3.6.1.2.1.31.1.1.1.18 (вместе с трейлером '.' входит в full_oid) # # full_oid: .1.3.6.1.2.1.31.1.1.1.1.1 # tmp_oid: .1.3.6.1.2.1.31.1.1.1.1 (вместе с трейлером '.' входит в full_oid) # Временный OID, полученный из конфигурационного файла, и в который уже подставлены # пользовательские параметры tmp_oid = prepare_oid(request_param.copy(), dataset[k], model, target_ip) # Проверяем, есть ли значение временного OID в полном OID if tmp_oid + trailer in full_oid + trailer: # Получаем оставшуюся часть от OID remainder = full_oid.replace(tmp_oid + '.', '') # Если используем метод get, оставшаяся часть будет равна iid if get_notwalk: remainder = var.oid_index # Альтернативный вариант для использования нескольких # последних чисел OID в имени подраздела, например '7.100' if k.count('.') > 1: remainder = ".".join( full_oid.split(".") [-k.count('.'):]) # Разбиваем имя параметра по ':'. Если все разбилось, то в первой части будет # "форматтер", который и применяем. splitted_prep_k = prep_k.split(':') if len(splitted_prep_k) == 2: try: formatter = getattr( helpers, splitted_prep_k[0]) prep_k = splitted_prep_k[1] value = formatter(var.value) except AttributeError: logging.warning( f'Formatter {splitted_prep_k[0]} not found.' ) value = var.value else: if var.value == 'NOSUCHINSTANCE': value = '' else: value = var.value # Например в конфиге указан OID 1.2.3.2.1, tag будет 1.2.3.2.1.X, iid - Y (может # быть пустым). # Полный OID (full_oid) будет 1.2.3.2.1.X.Y # Имя раздела (словаря) будет k, а подраздела (ключа метрики) - remainder if helper and prep_k not in data_for_helper: data_for_helper[prep_k] = {} elif prep_k not in json_resp['data']: json_resp['data'][prep_k] = {} if helper: data_for_helper[prep_k][remainder] = value else: json_resp['data'][prep_k][ remainder] = value # вызываем функцию хелпер, если она была указана if helper: json_resp['data'].update(helper(data_for_helper, target_ip)) # Если dataset является списком, выполняем для него set-операции if isinstance(dataset, list): varlist = [] for VarBindItem in dataset: prepaired_oid = prepare_oid(request_param.copy(), VarBindItem[:], model, target_ip) full_prepaired_oid = '.'.join(prepaired_oid[0:2]) varlist.append(( full_prepaired_oid, prepaired_oid[2], prepaired_oid[3], )) try: session.set_multiple(varlist) except (SystemError, EasySNMPError): json_resp['data'][method_name] = False else: json_resp['data'][method_name] = True time.sleep(swconfig.set_iter_delay) # Если dataset является кортежем, просто возвращаем его первый элемент. Это нужно для хранения # пользовательских словарей в конфиге swtoolz-core if isinstance(dataset, tuple): json_resp['data'][method_name] = dataset[0] return json_resp['data']
def frTftp(): # OID List # Protocol = .1.3.6.1.4.1.9.9.96.1.1.1.1.2.<Random Number> i 1 # Src File Type = .1.3.6.1.4.1.9.9.96.1.1.1.1.3.<Random Number> i 1 # Dest File Type = .1.3.6.1.4.1.9.9.96.1.1.1.1.4.<Random Number> i 4 # Srv Address=.1.3.6.1.4.1.9.9.96.1.1.1.1.5.<Random Number> a <IP Address> # DestFileName=.1.3.6.1.4.1.9.9.96.1.1.1.1.6.<Random Number> s <File Name> # Entry Row Stats = .1.3.6.1.4.1.9.9.96.1.1.1.1.14.<Random Number> i 4 rand = str(random.randint(100, 999)) swAddr = input("What is the IP address of the switch? ") comm = input("What is the SNMP Community? ") print(Color.YELLOW + "What is the IP address of the TFTP server?") print("Leave blank to use the built-in TFTP server and a local file. " + Color.END) tftpAddr = str(input("IP address: ") or "127.0.0.1") if tftpAddr == "127.0.0.1": print(Color.YELLOW + "The default file path is the current working " + "directory.") print("Your file MUST be inside or below this directory" + Color.END) fileName = input("Enter the filename (w/path if below default " + "directory): ") if tftpAddr != "127.0.0.1": tup = [ (".1.3.6.1.4.1.9.9.96.1.1.1.1.2." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.3." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.4." + rand, "4", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.5." + rand, tftpAddr, "a"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.6." + rand, fileName, "s"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.14." + rand, "4", "i"), ] session = easysnmp.Session(hostname=swAddr, community=comm, version=2) session.set_multiple(tup) time.sleep(2) input(Color.GREEN + Msgs.cont + Color.END) main_menu() else: print("Starting TFTP Server....") server = tftpy.TftpServer(os.getcwd()) server_thread = threading.Thread( target=server.listen, kwargs={ "listenip": "0.0.0.0", "listenport": 69 }, ) server_thread.start() time.sleep(2) print("TFTP Server started in current working directory.") ipAddr = [ l for l in ( [ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ][:1], [[( s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close(), ) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]], ) if l ][0][0] tup = [ (".1.3.6.1.4.1.9.9.96.1.1.1.1.2." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.3." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.4." + rand, "4", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.5." + rand, ipAddr, "a"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.6." + rand, fileName, "s"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.14." + rand, "4", "i"), ] session = easysnmp.Session(hostname=swAddr, community=comm, version=2) session.set_multiple(tup) time.sleep(10) server.stop(now=False) server_thread.join() input(Color.GREEN + Msgs.cont + Color.END) main_menu()
with open('database.csv') as f: reader = csv.reader(f) row_count = 0 for n in reader: if row_count == row: cell = n[col] return cell row_count += 1 for n in range(4): HOST = get_cell(0, n) try: session = easysnmp.Session(hostname=str(HOST), community='public', version=2) sys_walk = session.walk('.1.3.6.1.2.1.4.20.1.2') for item in sys_walk: sys_id=session.get('.1.3.6.1.2.1.1.5.0') sys_ipaddr=item.oid_index index=item.value sys_if = session.get('.1.3.6.1.2.1.2.2.1.2.' + index) sys_if_desc = session.get('.1.3.6.1.2.1.31.1.1.1.18.' + index) print(str(sys_id.value) + ',' + str(sys_if.value) + ',' + str(sys_if_desc.value) + ',' + str(sys_ipaddr)) except: print('Hostul ' + str(HOST) + ' e down!')
async def handle_get(request): answer = { 'request': { 'user': None, 'target': None, 'comm_index': None, 'data': [], 'errors': [], }, 'response': { 'target': None, 'sys_descr': None, 'sys_uptime': None, 'sys_name': None, 'sys_location': None, 'model': None, 'query_time': None, 'data': {}, }, } answer['request'].update(parse_request(request, swconfig.users)) answer['response']['target'] = answer['request']['target'] # Получаем SNMP-Community для устройства snmp_comm = swconfig.users[answer['request']['user']][answer['request'] ['comm_index']] # Создаем SNMP-сессию session = easysnmp.Session(hostname=answer['request']['target'], community=snmp_comm, version=2, retries=swconfig.snmp_retries, use_numeric=True, timeout=swconfig.snmp_timeout) # Фиксируем текущее время start_time = time.time() try: # Выполняем опрос параметров из default_info snmp_default_params = session.get(list(swconfig.default_info.values())) except EasySNMPTimeoutError: # Устройство недоступно, выставляем модель в 'None' answer['response']['model'] = 'None' else: # Помещаем в словарь результаты опроса параметров из default_info for def_param_index, def_param in enumerate(swconfig.default_info): answer['response'][def_param] = snmp_default_params[ def_param_index].value # Получаем идентификатор модели answer['response']['model'] = get_model( answer['response']['sys_name'], answer['response']['sys_descr'], models.models_by_desc) # Если в списке команд (методов) есть зарезервированная команда (метод), то выполняем опрос # оборудования даже если оно недоступно forced = False for request_param in answer['request']['data']: if len(set(request_param.values()) & set(swconfig.forced_mtd)) > 0: forced = True # Работаем, если устройство доступно (определили модель) или выставлен флаг 'forced' if answer['response']['model'] != 'None' or forced: # Пробуем импортировать модуль, описывающий методы для данной модели try: device_module = importlib.import_module( answer['response']['model']) importlib.reload(device_module) except ImportError: logging.error( f"Can't import module '{answer['response']['model']}' for '{answer['request']['target']}'!" ) else: data_from_device = process_device( device_module, answer['request']['data'], answer['response'], answer['request']['target'], snmp_comm, answer['response']['model'], request) answer['response']['data'] = data_from_device # Время, затраченное на опрос answer['response']['query_time'] = str( int((time.time() - start_time) * 1000)) return web.json_response(answer)
help="Warning threshold (percent)", required=False, type=int) parser.add_argument("-c", "--critical", help="Critical threshold (percent)", required=False, type=int) args = parser.parse_args() hostname = args.hostname community = args.community try: s = easysnmp.Session(hostname=hostname, community=community, version=2) except: print("UNKNOWN - unable to establish SNMP connection to the host") sys.exit(3) try: chargevalue = int( s.get('1.3.6.1.2.1.33.1.2.4.0').value) # upsEstimatedChargeRemaining except: print("UNKNOWN - unable to get upsEstimatedChargeRemaining variable") sys.exit(3) exitstatus = "OK" exitcode = 0 if args.critical and chargevalue < args.critical:
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import easysnmp import argparse import sys import json parser = argparse.ArgumentParser() parser.add_argument("-m", "--meruhost", help="Hostname of the meru controller",required=True) parser.add_argument("-C","-c", "--community", help="SNMP community of the meru controller",required=True) parser.add_argument("-i","--index",help="Index of the AP in the SNMP table",required=True,type=int) args = parser.parse_args() snmp_session = easysnmp.Session(hostname=args.meruhost,community=args.community, version=2) try: desc = snmp_session.get(('.1.3.6.1.4.1.15983.1.1.4.2.1.1.2',args.index)).value avstatus = int(snmp_session.get(('.1.3.6.1.4.1.15983.1.1.4.2.1.1.27',args.index)).value) except: print("UNKNOWN - Unable to get SNMP infos. Is the host reachable and the community correct?") sys.exit(3) if avstatus == 1: state = 2 message = "availabilityStatus is Power off" elif avstatus == 2: state = 2 message = "availabilityStatus is Offline" elif avstatus == 3:
def toTftp(): # OID List # Protocol = .1.3.6.1.4.1.9.9.96.1.1.1.1.2.<Random Number> i 1 # Src File Type = .1.3.6.1.4.1.9.9.96.1.1.1.1.3.<Random Number> i 4 # Dest File Type = .1.3.6.1.4.1.9.9.96.1.1.1.1.4.<Random Number> i 1 # Srv Address=.1.3.6.1.4.1.9.9.96.1.1.1.1.5.<Random Number> a <IP Address> # DestFileName=.1.3.6.1.4.1.9.9.96.1.1.1.1.6.<Random Number> s <File Name> # Entry Row Stats = .1.3.6.1.4.1.9.9.96.1.1.1.1.14.<Random Number> i 4 rand = str(random.randint(100, 999)) swAddr = input("What is the IP address of the switch? ") comm = input("What is the SNMP Community? ") print(Color.YELLOW + "What is the IP address of the TFTP server?") print("Leave blank to use the built-in TFTP server. " + Color.END) tftpAddr = str(input("IP address: ") or "127.0.0.1") fileName = input("Enter the filename (Optional: w/Path ): ") nameOnly = fileName.split("/")[-1] if tftpAddr != "127.0.0.1": tup = [ (".1.3.6.1.4.1.9.9.96.1.1.1.1.2." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.3." + rand, "4", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.4." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.5." + rand, tftpAddr, "a"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.6." + rand, fileName, "s"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.14." + rand, "4", "i"), ] session = easysnmp.Session(hostname=swAddr, community=comm, version=2) session.set_multiple(tup) time.sleep(2) input(Color.GREEN + Msgs.cont + Color.END) main_menu() else: print("Starting TFTP Server....") server = tftpy.TftpServer(os.getcwd()) server_thread = threading.Thread( target=server.listen, kwargs={ "listenip": "0.0.0.0", "listenport": 69 }, ) server_thread.start() time.sleep(2) print("TFTP Server started in current working directory.") ipAddr = [ l for l in ( [ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ][:1], [[( s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close(), ) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]], ) if l ][0][0] tup = [ (".1.3.6.1.4.1.9.9.96.1.1.1.1.2." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.3." + rand, "4", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.4." + rand, "1", "i"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.5." + rand, ipAddr, "a"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.6." + rand, nameOnly, "s"), (".1.3.6.1.4.1.9.9.96.1.1.1.1.14." + rand, "4", "i"), ] session = easysnmp.Session(hostname=swAddr, community=comm, version=2) session.set_multiple(tup) time.sleep(2) success = os.path.isfile(os.getcwd() + "/" + nameOnly) if success is True: print(Color.GREEN + "Success!" + Color.END) server.stop(now=False) server_thread.join() input(Color.GREEN + Msgs.cont + Color.END) main_menu() else: print(Color.RED + "I failed to download the config." + Color.END) server.stop(now=False) server_thread.join() yn = input("Would you like to try again? [Y/n] ") if yn == "Y" or yn == "yes" or yn == "": toTftp() else: main_menu()
def sess_v3(): return easysnmp.Session(**sess_v3_args())
def get_interfaces(self): """ Walks trough the and fetches IP address and IF-MIB::ifIndex :return: """ # If device is on ignore list skip interface discovery # Interfaces dictionary will be empty if self.ignored: self.logger.info("Device ignored. SKipping...") return True # Setup SNMP session try: self.logger.debug("Establishing SNMP session to '%s'" % self.hostname) self.session = easysnmp.Session( hostname=self.hostname, community=self.community, use_numeric=True, version=2, timeout=self.config.get_snmp_timeout(), retries=self.config.get_snmp_retries(), abort_on_nonexistent=True) # Fetch HSRP VIP addresses hsrp_addresses = self._get_hsrp_addresses() """ Implemented OID IP-MIB::ipAdEntIfIndex (1.3.6.1.2.1.4.20.1.2) is apparently deprecated. The new IP-MIB::ipAddressIfIndex is not implemented on most network devices. """ # Compiled regexp pattern - ipAdEntIfIndex + important dot ;) oid_pattern = re.compile(re.escape('.1.3.6.1.2.1.4.20.1.2.')) # Walk trough the IP-MIB::ipAdEntIfIndex tree. Results are in format: # .1.3.6.1.2.1.4.20.1.2.10.170.0.129 = INTEGER: 8 # .1.3.6.1.2.1.4.20.1.2.10.170.1.1 = INTEGER: 10 # OID ends here-^|^- IP starts here ^- ifIndex # etc... interface_address_results = self.session.walk( '.1.3.6.1.2.1.4.20.1.2') self.logger.info("Device has %d IP addresses" % len(interface_address_results)) for interface_address_result in interface_address_results: # IF-MIB::ifIndex later used to get IF-MIB::ifName if_index = int(interface_address_result.value) # If this is the first time encountering this ifIndex, # create DeviceInstance if if_index not in self.interfaces: # Some devices will have loopback IP and ifIndex # But no ifName associated with that ifIndex # We can skip those since we can't make PTRs try: self.logger.debug( "Create DeviceInterface object for ifIndex:%d" % if_index) self.interfaces[if_index] = DeviceInterface( self, if_index) except easysnmp.EasySNMPNoSuchInstanceError: self.logger.warning( "SNMP returned NOSUCHINSTANCE for ifIndex:%d" % if_index) continue # Remove the part of the OID we used to walk on. Leave just the IP address part. # Add it to interface ip_address = '.'.join([ re.sub(oid_pattern, '', interface_address_result.oid), interface_address_result.oid_index ]) self.logger.debug("Found '%s' address on ifIndex:%d" % (self.host, if_index)) # If there's HSRP VIP address on this interface add it to interface vip addresses # Pop removes the key from dict so we don't add the same list multiple times self.interfaces[if_index].add_vip_addresses( hsrp_addresses.pop(if_index, [])) # Add polled IP to interface IP list self.interfaces[if_index].add_ip_address(ip_address) return True except easysnmp.EasySNMPError as e: self.logger.error("Failed to connect to '%s': %s" % (self.hostname, e)) return False
def sess(sess_args): return easysnmp.Session(**sess_args)
#below commands used to skip first row of the csv which is the heading next(file) #looping over the device file for line in file: dev_name = line[1] ip = line[2] print("Testing Reachability .. %s ..IP address ..%s" % (dev_name, ip)) #calling a subprocess to ping ip addresses , if devices are reachable to to try snmp function ping_reply = subprocess.call( ['ping', '-c', '3', '-w', '3', '-q', '-n', ip], stdout=subprocess.PIPE) if ping_reply == 0: status = "%s is Reachable" % ip print(status) #following command in easysnmp uses the ip from the csv , along with a community string , with version 2 . This part is editable to suit the needs of community string, snmp version. session = easysnmp.Session(hostname='%s' % ip, community='NmSm0n1tor', version=2) #an example using snmpv3 walk with auth , privacy is not used , then "auth_without_privacy" is as the security_level parameter . #session = easysnmp.Session(hostname='%s'%ip,version=3,security_level="auth_with_privacy",security_username="******",auth_protocol="SHA",auth_password='******',privacy_protocol="AES",privacy_password="******" try: #trying to get the sysdescription oid description = session.get('.1.3.6.1.2.1.1.1.0') #convert the value for a string and look for "SNMP Variable" in the output as it indicates a sucessful walk description_mod = str(description) if "SNMPVariable" in description_mod: State = "SNMP Ok" print(State) else: State = "SNMP Error" print(State) #catching out basic snmp errors to indicate an SNMP or community problem