tarrac

Untitled

Mar 29th, 2023
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.58 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import subprocess
  4. import netmiko
  5.  
  6. import textfsm
  7.  
  8.  
  9. logger = netmiko.logging.getLogger(__file__)
  10. logger.setLevel(netmiko.logging.DEBUG)
  11.  
  12. #проверка доступности хоста
  13. def check_device (host):
  14.       result=subprocess.run(['ping',str(host),'-c','1','-W','1'],stdout=subprocess.DEVNULL).returncode
  15.       return result
  16.  
  17. #подключение к устройству
  18. def connection_to_dev(device,command):
  19.     try:
  20.         with netmiko.ConnectHandler(**device) as ssh:
  21.             # print ('>>>connect to host', device['ip'])
  22.             # ssh.enable()
  23.             result = ssh.send_command(command)
  24.             if 'Incomplete' in result:
  25.                 print('Error in command')
  26.  
  27.         return result
  28.     except Exception as e:
  29.         print(e)
  30.         print('>>>netmiko_return_error', device['ip'])
  31.  
  32.  
  33. #textfsm  парсинг вывода с коммутатора sh version/sh switch
  34. def parse_output(output,template = './templates/sh_version_snr.templates'):
  35.     try:
  36.         print(template)
  37.         with open(template) as f:
  38.             re_table = textfsm.TextFSM(f)
  39.         result = re_table.ParseText(output)
  40.         return result
  41.     except Exception as e:
  42.         raise e
  43.         print ('>>>no open file:',template)
  44.  
  45.  
  46.  
  47. # text = '''System Description   - JetStream 8-Port Gigabit Smart PoE Switch with 2 SFP Slots
  48. # System Name          - sw-2.14.3-Mira_pr-t_18k5
  49. # System Location      - MO_Himki_Mira_pr-t_18k5
  50. # Contact Information  - omt@himkismi.ru
  51. # Hardware Version     - T1500G-10PS 2.0
  52. # Software Version     - 2.0.0 Build 20180330 Rel.44639(s)
  53. # Bootloader Version   - TP-LINK  BOOTUTIL(v1.0.0)
  54. # Mac Address          - 98-DA-C4-27-05-46
  55. # Serial Number        - 2194738000297
  56. # System Time          - 2023-03-10 12:20:47
  57. # Running Time         - 151 day - 1 hour - 38 min - 12 sec'''
  58. # print(text)
  59. # print(parse_output(text, './templates/sh_version_tplink.templates'))
  60. # print(parse_output(text, './templates/sh_version_tplink.templates'))
  61. # exit()
  62. # если ввели argv не то, но выводим хелп
  63. # try:
  64. #   # templates=sys.argv[1]
  65. #   # command=' '.join(sys.argv[2:])
  66. #
  67. #   # template =  "templates/sh_version_snr.templates"
  68. #   template =  "templates/sh_version_tplink.templates"
  69. #   # command = "sh version"
  70. #   command = ['en', "sho system-info"]
  71. #   # print ('templates:',templates,'\ncommand:',command)
  72. # except:
  73. #  print('''неверные аргументы
  74. # - первый аргумент templates пример. ./templates/sh_version_snr.templates
  75. # - второй аргумент 'sh version' / 'sh switch'
  76. # ''')
  77. # subnet=ipaddress.ip_network('192.168.0.100/32')
  78. default_param={
  79.     'device_type':'cisco_ios_telnet',
  80.     'username':'smena',
  81.     'password':'himkisila',
  82.     'secret': 'himkisila',
  83.     'verbose':True
  84. }
  85. # default_param={'device_type':'cisco_ios_telnet','username':'serj','password':'hgtelecom','verbose':False}
  86. command='sho in eth sta'
  87. # commands=['en', "sho system-info"]
  88. host = '172.16.40.151'
  89. if check_device(host) == 1:
  90.     default_param.update({'ip': str(host)})
  91.     result = connection_to_dev(default_param, command)
  92.     for i in result.split('\n')[3:]:
  93.         port_info = [x for x in i.split(' ') if x!='']
  94.         # print(port_info)
  95.         if port_info[4] in ['1925', '2225', '1929']:
  96.             # print(port_info)
  97.             command = f'sho mac-address-table in eth {port_info[0]}'
  98.             port_i = connection_to_dev(default_param, command).split('\n')[3:][0].split(' ')[1]
  99.             print(host, port_info[0], port_i, sep='\t')
  100. exit()
Add Comment
Please, Sign In to add comment