Advertisement
andreypaste

Untitled

Feb 14th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.02 KB | None | 0 0
  1. #!/usr/bin/env python3.6
  2.  
  3. import os
  4. import paramiko
  5. import logging
  6. import time
  7.  
  8.  
  9. def _connect(list_ip):
  10. host = '10.1.10.2'
  11. user = 'hell'
  12. port = 22
  13. key_path = '/home/gilbert/.ssh/id_rsa'
  14. passphrase_ssh = 'supersecret'
  15. ssh = paramiko.SSHClient()
  16. # Добавляем ключ сервера в список известных хостов
  17. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  18.  
  19. print("connecting")
  20.  
  21. try:
  22. ssh.connect(hostname=host, username=user, key_filename=key_path, port=port, passphrase=passphrase_ssh)
  23. print('connected')
  24. time.sleep(1)
  25. except paramiko.ssh_exception.NoValidConnectionsError:
  26. # Просто печатаем и записываем в лог, что не получилось подключиться.
  27. # Скрипт продолжит работу после блока try except.
  28. logger.debug("Could not connect to host {}".format(host))
  29. print("Could not connect to host {}".format(host))
  30. except Exception as e:
  31. # Производит какие-то манипуляции, если у нас возникла кака-то ошибка.
  32. print("Some error: %s" % e)
  33. # Тут скрипт закончит работу и выйдет с кодом 2
  34. raise SystemExit(2)
  35. for k in list_ip:
  36. if len(k.split('.')[3]) < 3:
  37. # Уже не помню для чего именно надо добавлять пробел если последний актет меньше трёх символов
  38. k += ' '
  39. print('Last otktet < 3')
  40. # ssh.connect(hostname=host, username=user, password=passwd, port=port)
  41. stdin, stdout, stderr = ssh.exec_command('sh ip arp')
  42. data = stdout.read() + stderr.read()
  43. # Если в арпах Incomplete значит адрес не используется в данный момент
  44. if b'Vlan10' in data:
  45. print('Vlan10: {}'.format(data))
  46.  
  47. ssh.close()
  48.  
  49. *******************************************************************************
  50.  
  51. if __name__ == "__main__":
  52. logger = logging.getLogger('example-script')
  53. # файл куда логировать
  54. try:
  55. hdlr = logging.FileHandler('/var/log/example-script.log')
  56. except PermissionError:
  57. print("Недостаточно прав для создания или записи в файл лога.")
  58. raise SystemExit(2)
  59. # формат лога
  60. formatter = logging.Formatter('%(asctime)s %(process)d/%(threadName)s %(levelname)s : %(message)s')
  61. hdlr.setFormatter(formatter)
  62. logger.addHandler(hdlr)
  63. # Уровень лога
  64. logger.setLevel(logging.DEBUG)
  65.  
  66. arr = ['192.168.0.1', '192.168.0.2']
  67. # for i in range(1, 5):
  68. # if os.system("ping -c 3 -W 3 185.162.93.%s" % i) != 0:
  69. # arr.append('185.162.93.%s' % i)
  70. #
  71. # for j in arr:
  72. # print(j)
  73.  
  74. _connect(arr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement