Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3.6
- import os
- import paramiko
- import logging
- import time
- def _connect(list_ip):
- host = '10.1.10.2'
- user = 'hell'
- port = 22
- key_path = '/home/gilbert/.ssh/id_rsa'
- passphrase_ssh = 'supersecret'
- ssh = paramiko.SSHClient()
- # Добавляем ключ сервера в список известных хостов
- ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- print("connecting")
- try:
- ssh.connect(hostname=host, username=user, key_filename=key_path, port=port, passphrase=passphrase_ssh)
- print('connected')
- time.sleep(1)
- except paramiko.ssh_exception.NoValidConnectionsError:
- # Просто печатаем и записываем в лог, что не получилось подключиться.
- # Скрипт продолжит работу после блока try except.
- logger.debug("Could not connect to host {}".format(host))
- print("Could not connect to host {}".format(host))
- except Exception as e:
- # Производит какие-то манипуляции, если у нас возникла кака-то ошибка.
- print("Some error: %s" % e)
- # Тут скрипт закончит работу и выйдет с кодом 2
- raise SystemExit(2)
- for k in list_ip:
- if len(k.split('.')[3]) < 3:
- # Уже не помню для чего именно надо добавлять пробел если последний актет меньше трёх символов
- k += ' '
- print('Last otktet < 3')
- # ssh.connect(hostname=host, username=user, password=passwd, port=port)
- stdin, stdout, stderr = ssh.exec_command('sh ip arp')
- data = stdout.read() + stderr.read()
- # Если в арпах Incomplete значит адрес не используется в данный момент
- if b'Vlan10' in data:
- print('Vlan10: {}'.format(data))
- ssh.close()
- *******************************************************************************
- if __name__ == "__main__":
- logger = logging.getLogger('example-script')
- # файл куда логировать
- try:
- hdlr = logging.FileHandler('/var/log/example-script.log')
- except PermissionError:
- print("Недостаточно прав для создания или записи в файл лога.")
- raise SystemExit(2)
- # формат лога
- formatter = logging.Formatter('%(asctime)s %(process)d/%(threadName)s %(levelname)s : %(message)s')
- hdlr.setFormatter(formatter)
- logger.addHandler(hdlr)
- # Уровень лога
- logger.setLevel(logging.DEBUG)
- arr = ['192.168.0.1', '192.168.0.2']
- # for i in range(1, 5):
- # if os.system("ping -c 3 -W 3 185.162.93.%s" % i) != 0:
- # arr.append('185.162.93.%s' % i)
- #
- # for j in arr:
- # print(j)
- _connect(arr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement