Advertisement
Guest User

Untitled

a guest
Dec 27th, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.95 KB | None | 0 0
  1. import telnetlib
  2. import logging
  3. from logging import FileHandler
  4. from logging import Formatter
  5. import threading
  6. import datetime
  7. import time
  8. import csv
  9.  
  10.  
  11. LOG_FORMAT = ("%(message)s")
  12. LOG_LEVEL = logging.INFO
  13.  
  14. # логгер для записи в файл
  15. MESSAGING_LOG_FILE = "information.csv"
  16. messaging_logger = logging.getLogger("messaging")
  17. messaging_logger.setLevel(LOG_LEVEL)
  18. messaging_logger_file_handler = FileHandler(MESSAGING_LOG_FILE, "w", encoding = "UTF-8")
  19. messaging_logger_file_handler.setLevel(LOG_LEVEL)
  20. messaging_logger_file_handler.setFormatter(Formatter(LOG_FORMAT))
  21. messaging_logger.addHandler(messaging_logger_file_handler)
  22.  
  23. # логгер для вывода в консоль
  24. console_logger = logging.getLogger("console")
  25. console_logger.setLevel(LOG_LEVEL)
  26. console_logger.addHandler(logging.StreamHandler())
  27.  
  28.  
  29.  
  30. # класс менеджер для запуска потока и обработки callback`a
  31. class Manager():
  32.     # запуск потока
  33.     def Test(self, func, router_data, num):
  34.         console_logger.info('Получение данных от роутера по адресу: '+ num)
  35.         MyThread(self.on_thread_finished, target=func, args=[router_data], kwargs={'num': num}).start()
  36.  
  37.     # callback-функция, вызывается после завершения потока
  38.     def on_thread_finished(self, data):
  39.         console_logger.info("Получение данных от роутера по адресу: " + data[0] + " завершилось: " + data[1])
  40.  
  41. # класс потока с проверкой на исключения и вывод их в callback`e
  42. class MyThread(threading.Thread):
  43.     def __init__(self, callback, *args, **kwargs):
  44.         threading.Thread.__init__(self, *args, **kwargs)
  45.         self.callback = callback
  46.         self.num = kwargs['kwargs']['num']
  47.  
  48.         run_original = self.run  # ссылка на оригинальный метод run
  49.  
  50.         def run_with_except_hook(*args2, **kwargs2):
  51.             try:
  52.                 run_original(*args2, **kwargs2) # вызов оригинального run
  53.             # отлов ошибок
  54.             except Exception as e:
  55.                 data = (self.num, 'с ошибкой {}'.format(type(e)))
  56.                 self.callback(data)
  57.             else:
  58.                 data = (self.num, 'успешно')
  59.                 self.callback(data)
  60.  
  61.         self.run = run_with_except_hook  # переопределение метода run
  62.  
  63. def parse_csv(filename):
  64.     with open(filename, encoding='utf-8') as f:
  65.         next(f)  # пропускаем заголовки
  66.         yield from csv.reader(f)
  67.  
  68.  
  69. # функция для запуска в потоке
  70. def check_router(router_data, **kwargs):
  71.     adress, WANip, VPNip, user, password = router_data
  72.  
  73.     console_logger.info(adress + ', ' + WANip)
  74.  
  75.     model = 'empty'
  76.     release = 'empty'
  77.     sn = 'empty'
  78.     mac = 'empty'
  79.     des = 'empty'
  80.     status = ''
  81.  
  82.     # Автологин
  83.     start_time1 = time.time()
  84.     rez_str = adress + ';' + WANip + ';' + VPNip
  85.     try:
  86.         tn = telnetlib.Telnet(WANip)
  87.         status = 'Connection success!'
  88.     except Exception as e:
  89.         status = 'Connection failed!'
  90.         console_logger.info('Не удалось подключиться к роутеру по адресу ' + adress)
  91.         messaging_logger.info(rez_str + ';' + model + ';' + release + ';' + sn + ';' + mac + ';' + des + ';' + status + '\n')
  92.         console_logger.info('--- Сбор данных закончен за ---')
  93.         t = time.time() - start_time1
  94.         console_logger.info('---------- '+ str(t) +' секунд -------------')
  95.     else:
  96.         try:
  97.             tn.read_until(b'Login: ', timeout=2)
  98.             tn.write(user.encode('ascii') + b'\n')
  99.             tn.read_until(b'Password: ', timeout=2)
  100.             tn.write(password.encode('ascii') + b'\n')
  101.             tn.read_until(b'(config)> ', timeout=1)
  102.         except Exception as f:
  103.             console_logger.info('Не удалось залогиниться к роутеру по адресу ' + adress)
  104.         else:
  105.             # Собираем инфу из роутера
  106.             tn.read_until(b'(config)> ', timeout=2)
  107.             tn.write('show version'.encode('ascii') + b'\n')
  108.             time.sleep(2)
  109.  
  110.             # Сбор модели
  111.             out = tn.read_very_eager().decode('ascii')
  112.             out = out.split(' ')
  113.             if 'description:' in out:
  114.                 i1 = out.index('description:')
  115.                 model = (out[i1 + 1]) + ' ' + (out[i1 + 2]) + ' ' + (out[i1 + 3]).strip('\r\n\r\n(config)>')
  116.             elif 'device:' in out:
  117.                 i2 = out.index('device:')
  118.                 model = (out[i2 + 1]) + ' ' + (out[i2 + 2]).strip('\r\n')
  119.             else:
  120.                 model = 'неизвестная модель'
  121.             if 'release:' in out:
  122.                 i3 = out.index('release:')
  123.                 release = (out[i3 + 1]).strip('\r\n')
  124.             else:
  125.                 release = 'Нужен повторный опрос'
  126.             tn.read_until(b'(config)> ', timeout=2)
  127.             tn.read_until(b'(config)> ', timeout=2)
  128.             tn.write('show interface PPTP0'.encode('ascii') + b'\n')
  129.             time.sleep(2)
  130.  
  131.             # Сбор инфы по VPN
  132.             out1 = tn.read_very_eager().decode('utf-8')
  133.             out1 = out1.split(' ')
  134.             if 'description:' in out1:
  135.                 i4 = out1.index('description:')
  136.                 des = (out1[i4 + 1]).strip('\r\n')
  137.             else:
  138.                 des = 'Подключение VPN не настроено'
  139.             # Сбор Серийного номера
  140.             tn.write('show defaults'.encode('ascii') + b'\n')
  141.             time.sleep(6)
  142.             out2 = tn.read_very_eager().decode('ascii')
  143.             out2 = out2.split(' ')
  144.             if 'serial:' in out2:
  145.                 i5 = out2.index('serial:')
  146.                 sn = (out2[i5 + 1]).strip('\r\n')
  147.             else:
  148.                 sn = 'В FW нет serial'
  149.             # Сбор MAC Адреса
  150.             tn.read_until(b'(config)> ', timeout=1)
  151.             tn.write('show interface ISP'.encode('utf-8') + b'\n')
  152.             time.sleep(2)
  153.             out3 = tn.read_very_eager().decode('utf-8')
  154.             out3 = out3.split(' ')
  155.             if 'mac:' in out3:
  156.                 i6 = out3.index('mac:')
  157.                 mac = (out3[i6 + 1]).strip('\r\n')
  158.             else:
  159.                 mac = ''
  160.  
  161.             # #Сбор конфига
  162.             tn.write('show running-config'.encode('ascii') + b'\n')
  163.             time.sleep(2)
  164.             out4 = tn.read_very_eager().decode('utf-8')
  165.             out4 = out4.split('\r\n')
  166.  
  167.             # Запись данных в файл (Buckup config)
  168.             handle = open('{}.txt'.format(WANip).encode('ascii'), 'w')
  169.             for l in out4:
  170.                 handle.write (l+'\n')
  171.             handle.close()
  172.         finally:
  173.             messaging_logger.info(rez_str + ';' + model + ';' + release + ';' + sn + ';' + mac + ';' + des + ';' + status + '\n')
  174.        
  175.         t = time.time() - start_time1
  176.         console_logger.info('--- Сбор данных закончен за ------ ' + str(t) + ' секунд -------------')
  177.            
  178.    
  179.  
  180. def main():
  181.     start_time = time.time()
  182.     m = Manager() # менеджер для запуска потоков
  183.  
  184.     # делаем список из файла
  185.     routers = list(parse_csv('C:\\py\\table1.csv'))
  186.  
  187.     # запуск потоков - по числу роутеров
  188.     while len(routers) > 0:
  189.         data = routers.pop(0)[0].split(';')
  190.         # запуск потока
  191.         m.Test(check_router, router_data=data, num=data[0])
  192.  
  193.     print('--- Скрипт завершил работу за --- %s секунд ---' % (time.time() - start_time))
  194.    
  195.  
  196.  
  197.    
  198. if __name__ == '__main__':
  199.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement