通过python的paramiko模块获取cisco交换机的配置

import paramiko
import time
import os
import threading,Queue

class MyExpection(Exception):
    pass

class ThreadPool(object):
    def __init__(self, maxsize):
        self.maxsize = maxsize
        self._q = Queue.Queue(self.maxsize)
        for i in range(self.maxsize):
            self._q.put(threading.Thread)

    def getThread(self):
        return self._q.get()

    def addThread(self):
        self._q.put(threading.Thread)

def show_conf(remote_session,hostname):
    remote_session.send('terminal length 0
')
    time.sleep(0.1)
    remote_session.send('show run
')
    time.sleep(1.6)
    buff = remote_session.recv(655350)
    #print(buff)
    file_path = os.path.join(os.path.split(os.path.realpath(__file__))[0],'conf/')
    with open(file_path + str(hostname) + '.conf', 'wb') as f:
        f.write(buff)
    buff =  ''
    remote_session.send('show vlan
')
    time.sleep(0.2)
    buff = remote_session.recv(655350)
    file_path = os.path.join(os.path.split(os.path.realpath(__file__))[0],'vlan/')
    with open(file_path + str(hostname) + '.vlan', 'wb') as f:
        f.write(buff)
    os.system('sh sedFile.sh %s'%hostname)
    remote_session.send('exit
')
    print('%s is OK'%hostname)

def ssh(hostname,username,pw,en_pw,pool):
    port = 22
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(hostname, port, username, pw, timeout=5)
        remote_session = client.invoke_shell()
        time.sleep(0.2)
        buff = remote_session.recv(65535).decode()
        if buff.endswith('>'):
            remote_session.send('en
')
            time.sleep(0.2)
            buff = remote_session.recv(65535).decode()
            if buff.endswith('Password: '):
                remote_session.send('%s
'%en_pw)
                time.sleep(0.2)
                buff = remote_session.recv(65535).decode()
                if buff.endswith('Password: '):
                    raise MyExpection('`s enable password is incorrect')
                show_conf(remote_session, hostname)
        elif buff.endswith('#'):
            show_conf(remote_session, hostname)
    except MyExpection as e:
        print('%s is %s' % (hostname, e))
    except Exception as e:
        print('%s is %s'%(hostname,e))
    pool.addThread()

if __name__ == '__main__':
    t_list = []
    pool = ThreadPool(5)
    with open('list.txt','r') as f:
        for line in f:
            hostname,username,pw,en_pw  = line.strip().split('	')
            th = pool.getThread()
            t = th(target=ssh, args=(hostname,username,pw,en_pw,pool))
            t.start()
            t_list.append(t)
    for i in t_list:
        i.join()

  其中在该目录中有conf和vlan的文件夹,并且调用的那个shell如下:主要是为了剪切

#!/bin/bash
#
cd /home/hjc/switch/conf
file1=$1.conf
sed -ni '/Building configuration/,$p' $file1
sed -i '/Building configuration/d' $file1
sed -i '$d' $file1
cd /home/hjc/switch/vlan
file2=$1.vlan
sed -i '/show vlan/d' $file2
sed -i '$d' $file2

  而调用的那个list.txt主要是存放ip、user、password、enable_password,

  写的很烂,但实现了想要的功能,还算比较开心,后面还会改进可以判断登录的是哪一品牌的交换机,然后做出不同的判断和发送的信息。

原文地址:https://www.cnblogs.com/hjc4025/p/10137130.html