通過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\n')
    time.sleep(0.1)
    remote_session.send('show run\n')
    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\n')
    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\n')
    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\n')
            time.sleep(0.2)
            buff = remote_session.recv(65535).decode()
            if buff.endswith('Password: '):
                remote_session.send('%s\n'%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('\t')
            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,

  寫的很爛,但實現了想要的功能,還算比較開心,后面還會改進可以判斷登錄的是哪一品牌的交換機,然后做出不同的判斷和發送的信息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM