Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- import subprocess
- import netmiko
- import textfsm
- logger = netmiko.logging.getLogger(__file__)
- logger.setLevel(netmiko.logging.DEBUG)
- #проверка доступности хоста
- def check_device (host):
- result=subprocess.run(['ping',str(host),'-c','1','-W','1'],stdout=subprocess.DEVNULL).returncode
- return result
- #подключение к устройству
- def connection_to_dev(device,command):
- try:
- with netmiko.ConnectHandler(**device) as ssh:
- # print ('>>>connect to host', device['ip'])
- # ssh.enable()
- result = ssh.send_command(command)
- if 'Incomplete' in result:
- print('Error in command')
- return result
- except Exception as e:
- print(e)
- print('>>>netmiko_return_error', device['ip'])
- #textfsm парсинг вывода с коммутатора sh version/sh switch
- def parse_output(output,template = './templates/sh_version_snr.templates'):
- try:
- print(template)
- with open(template) as f:
- re_table = textfsm.TextFSM(f)
- result = re_table.ParseText(output)
- return result
- except Exception as e:
- raise e
- print ('>>>no open file:',template)
- # text = '''System Description - JetStream 8-Port Gigabit Smart PoE Switch with 2 SFP Slots
- # System Name - sw-2.14.3-Mira_pr-t_18k5
- # System Location - MO_Himki_Mira_pr-t_18k5
- # Contact Information - omt@himkismi.ru
- # Hardware Version - T1500G-10PS 2.0
- # Software Version - 2.0.0 Build 20180330 Rel.44639(s)
- # Bootloader Version - TP-LINK BOOTUTIL(v1.0.0)
- # Mac Address - 98-DA-C4-27-05-46
- # Serial Number - 2194738000297
- # System Time - 2023-03-10 12:20:47
- # Running Time - 151 day - 1 hour - 38 min - 12 sec'''
- # print(text)
- # print(parse_output(text, './templates/sh_version_tplink.templates'))
- # print(parse_output(text, './templates/sh_version_tplink.templates'))
- # exit()
- # если ввели argv не то, но выводим хелп
- # try:
- # # templates=sys.argv[1]
- # # command=' '.join(sys.argv[2:])
- #
- # # template = "templates/sh_version_snr.templates"
- # template = "templates/sh_version_tplink.templates"
- # # command = "sh version"
- # command = ['en', "sho system-info"]
- # # print ('templates:',templates,'\ncommand:',command)
- # except:
- # print('''неверные аргументы
- # - первый аргумент templates пример. ./templates/sh_version_snr.templates
- # - второй аргумент 'sh version' / 'sh switch'
- # ''')
- # subnet=ipaddress.ip_network('192.168.0.100/32')
- default_param={
- 'device_type':'cisco_ios_telnet',
- 'username':'smena',
- 'password':'himkisila',
- 'secret': 'himkisila',
- 'verbose':True
- }
- # default_param={'device_type':'cisco_ios_telnet','username':'serj','password':'hgtelecom','verbose':False}
- command='sho in eth sta'
- # commands=['en', "sho system-info"]
- host = '172.16.40.151'
- if check_device(host) == 1:
- default_param.update({'ip': str(host)})
- result = connection_to_dev(default_param, command)
- for i in result.split('\n')[3:]:
- port_info = [x for x in i.split(' ') if x!='']
- # print(port_info)
- if port_info[4] in ['1925', '2225', '1929']:
- # print(port_info)
- command = f'sho mac-address-table in eth {port_info[0]}'
- port_i = connection_to_dev(default_param, command).split('\n')[3:][0].split(' ')[1]
- print(host, port_info[0], port_i, sep='\t')
- exit()
Add Comment
Please, Sign In to add comment