1. 程式人生 > >python腳本備份網絡設備配置文件

python腳本備份網絡設備配置文件

clas als elf 成功 conn txt 參數 brush som

# _*_ coding:utf-8 _*_

"""
__title__ = ‘網絡設備配置文件備份‘
__author__ = ‘Lucky‘
__date__ = ‘2018/08/23‘
"""

from logging import warning
from time import sleep,strftime,localtime
from os import mkdir
import telnetlib
import paramiko



class Telnet_Client:

    ‘‘‘初始化登錄參數,以及實例化telnet和ssh類‘‘‘
    def __init__(self,host_ip,username,password,port):
        self.telnet = telnetlib.Telnet()
        self.ssh = paramiko.SSHClient()
        self.host_ip = host_ip
        self.username = username
        self.password = password
        self.port = port

    def login_ssh_host(self):

        ‘‘‘自動添加策略,保存服務器的主機名和公鑰信息‘‘‘
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            self.ssh.connect(self.host_ip,self.port,self.username,self.password,timeout=8)
            print("\nssh(%s)連接成功." %self.host_ip)
            return True
        except:
            warning("\n網絡(%s)連接失敗!" %self.host_ip)
            input_string = input("\n請檢查網絡(%s)是否暢通[ssh]" %self.host_ip)
            return False

    def login_telnet_host(self):

        ‘‘‘可能有些機器遠程連接會連不上,這裏做異常捕獲‘‘‘
        try:
            self.telnet.open(self.host_ip,self.port,timeout=10)
        except:
            warning("\n網絡(%s)連接失敗!" %self.host_ip)
            input_string = input("\n請檢查網絡(%s)是否暢通[telnet]" % self.host_ip + "\n")
            return False
        else:

            ‘‘‘
                這裏用read_until方法進行匹配登錄字符是否為login,是的話輸入用戶名,最多等待10秒
                這裏在強調一下telnet需要傳入的內容為bytes,所以需要encode一下
            ‘‘‘
            self.telnet.read_until(b‘Username: ‘,timeout=10)
            self.telnet.write(self.username.encode(‘ascii‘) + b‘\n‘)

            # 等待Password出現後輸入密碼,最多等待10秒
            self.telnet.read_until(b‘Password: ‘,timeout=10)
            self.telnet.write(self.password.encode(‘ascii‘) + b‘\n‘)

            # 等待1秒給設備一個緩沖時間
            sleep(1)

            # read_very_eager()獲取上次程序執行的結果
            last_command_result = self.telnet.read_very_eager().decode(‘ascii‘)

            # 判斷上次結果是否有登錄錯誤的
            if ‘Login incorrect‘ not in last_command_result:
                print(‘\ntelnet(%s)登錄成功.‘ %self.host_ip)
                return True
            else:
                warning(‘\n登錄(%s)失敗,用戶名或密碼錯誤!‘ %self.host_ip)
                return False

    # 執行telnet命令
    def execute_some_command(self,
                             command_telnet_user,
                             command_telnet_password,
                            command_telnet_copy_to_ftp,
                             command_telnet_to_ftp_1,
                             command_telnet_to_ftp_2,
                            command_telnet_to_ftp_3):

        str_time = strftime("%Y%m%d", localtime())
        backup_cfg = self.host_ip + "_" + str_time + ".txt"

        # 執行傳入的命令,這裏也需要將傳入的命令進行encode處理
        self.telnet.write(command_telnet_user.encode(‘ascii‘) + b‘\n‘)
        self.telnet.write(command_telnet_password.encode(‘ascii‘))
        self.telnet.write(command_telnet_copy_to_ftp.encode(‘ascii‘))
        self.telnet.write(command_telnet_to_ftp_1.encode(‘ascii‘))
        self.telnet.write(command_telnet_to_ftp_2.encode(‘ascii‘))
        try:
            self.telnet.write(backup_cfg.encode(‘ascii‘) + command_telnet_to_ftp_3.encode(‘ascii‘))
        except Exception as e:
            print("telnet(%s)備份網絡配置文件失敗!" %self.host_ip)
        else:
            print("\ntelnet登錄(%s)後網絡配置文件備份成功." %self.host_ip)

        # 等待1秒給設備一個緩沖時間
        sleep(1)

        # 獲取命令執行結果
        # exec_command_result = self.telnet.read_very_eager().decode(‘ascii‘)
        # print(exec_command_result)

    # 執行ssh命令
    def execute_ssh_command(self,command):
        stdin, stdout, stderr = self.ssh.exec_command(command)

        # 等待1秒給設備一個緩沖時間
        sleep(1)

        result = stdout.readlines()
        str_time = strftime("%Y%m%d", localtime())
        # mkdir(str_time)
        with open(str_time + "\\" + self.host_ip + "_" + str_time + ".txt","w",encoding="utf-8") as result_ssh_obj:
            for line in result:
                try:
                    result_ssh_obj.write(line.strip() + "\n")
                except Exception as e:
                    print("備份(%s)設備上的網絡配置文件失敗,錯誤代碼為:%s" %(self.host_ip,e))
                else:
                    print("\nssh登錄(%s)後網絡配置文件備份成功." %self.host_ip)

    # 退出telnet函數
    def logout_telnet(self):
        self.telnet.write(b"exit\n")

    # 退出ssh函數
    def logout_ssh(self):
        self.ssh.close()

def main():
    str_time = strftime("%Y%m%d", localtime())
    mkdir(str_time)

    command_telnet_user = "enable\n"
    command_telnet_password = "123456\n"
    command_telnet_copy_to_ftp = "copy run tftp://192.168.2.2\n"
    command_telnet_to_ftp_1 = "\n"
    command_telnet_to_ftp_2 = "\n"
    command_telnet_to_ftp_3 = "\n"

    command_ssh = "show run"

    # ssh和telnet調用過程
    with open(‘ssh_host.txt‘, ‘r‘, encoding=‘utf-8‘) as ssh_obj,             open(‘telnet_host.txt‘, ‘r‘, encoding=‘utf-8‘) as telnet_obj:
        for ssh_ip in ssh_obj:
            # 根據類實例化一個ssh對象
            ssh_client = Telnet_Client(ssh_ip.strip(), ‘admin‘, ‘123456‘, ‘22‘)

            # 根據函數的返回值進行判斷是否繼續執行別的函數
            if ssh_client.login_ssh_host():
                ssh_client.execute_ssh_command(command_ssh)
                ssh_client.logout_ssh()

        for ip in telnet_obj:
            # 根據類實例化一個telnet對象
            telnet_client = Telnet_Client(ip.strip(), ‘admin‘, ‘123456‘, ‘23‘)

            # 根據函數的返回值進行判斷是否繼續執行別的函數
            if telnet_client.login_telnet_host():
                telnet_client.execute_some_command(command_telnet_user,
                                                   command_telnet_password,
                                                   command_telnet_copy_to_ftp,
                                                   command_telnet_to_ftp_1,
                                                   command_telnet_to_ftp_2,
                                                   command_telnet_to_ftp_3)
                telnet_client.logout_telnet()

if __name__ == ‘__main__‘:
    main()

  

python腳本備份網絡設備配置文件