netmiko 脚本连接路由器

问题描述

当我运行我的 Python 脚本时,我在 paramiko 库上遇到错误...

但是脚本的结果不理解。谁能帮忙解决这个问题..!?

这是错误

**Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py",line 2044,in _check_banner
    buf = self.packetizer.readline(timeout)
  File "/usr/local/lib/python3.5/dist-packages/paramiko/packet.py",line 353,in readline
    buf += self._read_timeout(timeout)
  File "/usr/local/lib/python3.5/dist-packages/paramiko/packet.py",line 540,in _read_timeout
    x = self.__socket.recv(128)
ConnectionResetError: [Errno 104] Connection reset by peer

在处理上述异常的过程中,又出现了一个异常

这是新的例外

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py",line 1893,in run
    self._check_banner()
  File "/usr/local/lib/python3.5/dist-packages/paramiko/transport.py",line 2049,in _check_banner
    'Error reading SSH protocol banner' + str(e)
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[Errno 104] Connection reset by peer

Script run time = 00:02:34**

这是脚本

#!/usr/bin/python3.6
#import ipaddress
import csv
import os
from os import listdir
from os.path import isfile,join,expanduser
import getpass
import threading
import logging
import re
import time
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException

#-----------------------------------------------------------
def get_wd():
    wd = os.path.expanduser('temp/')
    if not os.path.exists(wd):
        os.makedirs(wd)
    return wd
#-----------------------------------------------------------
def del_temp_files():
    list_temp_dir = os.listdir(wd)
    ext = (".json",".csv",".txt",".log")
    for item in list_temp_dir:
        if item.endswith(ext):
            os.remove(os.path.join(wd,item))


#----------------------------------------------------------------------
def ssh_connection(ip,ref,username,password):
    try:
        return ConnectHandler(device_type='cisco_ios',ip=ip,username=username,password=password)
    except Exception as error:
        logger.error('. %&%&%&%&%& {} {}   \t   {}'.format(ref,ip,error))
        with open ("{}conn_error.txt".format(wd),"a") as efile:
            efile.write('{} {} \n'.format(ref,ip))
#--------------------envoie de commande et stocker le resultat dans un fichier----------------------------------------------------
def get_worker(ip,device):
    try:
        result = device.send_command("show run | inc username")
        if "cisco" in result:
            usert="yes"
        else:
            usert="no"
        with open ("{}result.csv".format(wd),"a") as file1:
            file1.write('{} {}\n'.format(ref,usert))
    except Exception as error:
        logger.error(". Get Error  {}  {}   \t    {}".format(ref,error))
#-----------------------connection aux équipements--------------------------------------------------------
def main(ip,password):
    device = ssh_connection(ip,password)
    if device == None:
            sema.release()
            return
    output = get_worker(ip,device)
    device.disconnect()
    sema.release()
if __name__ == '__main__':

    wd = get_wd()
    del_temp_files()
    threads = []
    max_threads = 20
    sema = threading.BoundedSemaphore(value=max_threads)
    user = "cisco"
    passwd = "cisco"

    start_time = time.time()
    logger = logging.getLogger("LOG")
    handler = logging.FileHandler("{}main.log".format(wd))
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
#--------------------------------------------------------------------
with open("/home/net/inventaire_routes/cisco.csv.save") as fh:
    devices = csv.reader(fh,delimiter=';')
    for host in devices:
        sema.acquire()
        ip = host[1]
        ref = host[0]
        thread = threading.Thread(target=main,args=(ip,user,passwd))
        threads.append(thread)
        thread.start()

elapsed_time = time.time() - start_time
print("Script run time = " + time.strftime("%H:%M:%s",time.gmtime(elapsed_time)))
#----------------------------------------------------------------------------------

我该如何解决这个问题..!??

解决方法


ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('192.16.16.2',username= 'admin',password= 'cisco')

stdin,stdout,stderr =ssh.exec_command("show run | inc username ")
output = stdout.readlines()
print('\n'.join(output))
ssh.close()






username admin privilege 15 password 7 00071A150754

Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/paramiko/file.py",line 66,in __del__
  File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py",line 1392,in close
  File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py",line 991,in shutdown_write
  File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py",line 963,in shutdown
  File "/usr/local/lib/python3.6/site-packages/paramiko/channel.py",line 1246,in _send_eof
  File "/usr/local/lib/python3.6/site-packages/paramiko/message.py",line 232,in add_int
TypeError: 'NoneType' object is not callable