您好,登錄后才能下訂單哦!
折騰了一天的裝飾器,貌似理解了其中的一點點...
#!/usr/bin/env python3 #coding=utf-8 import getpass from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException,NetMikoAuthenticationException def auth(Conn): def wrapper(ip,username,password): device = { 'device_type': 'cisco_ios', 'ip': ip, 'username': username, 'password': password, } try: connect = ConnectHandler(**device) connect.enable() except (EOFError, NetMikoTimeoutException): print(u" 網絡設備%s: 無法連接!請確認該設備IPAddress是否可達!"%ip) return except (EOFError, NetMikoAuthenticationException): print(u" 網絡設備%s: 用戶名與密碼錯誤!請確認賬號與密碼!" %ip) return Conn(ip,username,password,connect) return Conn return wrapper @auth def showInterface(ip,username,password,connect): res = connect.send_command('show ip int brief') print(res) connect.disconnect() @auth def showVersion(ip,username,password,connect): res = connect.send_command('show version') print(res) connect.disconnect() def main(): print(u"選項請輸入數字,如: 1、2") print(u"1. 查詢設備接口信息") print(u"2. 查詢設備版本信息") print("") runFunc = int(input(u'請輸入需要執行命令的選項: ')) input_ip = input("IPAddress: ") ipaddress = input_ip.split(",") username = input("Username: ") password = getpass.getpass() for ip in ipaddress: if runFunc == 1: showInterface(ip,username,password) if runFunc == 2: showVersion(ip,username,password) if __name__ == '__main__': main()
運執行上面的代碼,運行效果如下:
以下代碼用類也可以實現相一樣的結果,可以對比一下那個方便
#!/usr/bin/env python3 #coding=utf-8 import getpass from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException,NetMikoAuthenticationException class NWBackup(): def __init__(self): self.ip = input('IPAddress:') self.username = input('Username:') self.password = getpass.getpass() self.device={'device_type': 'cisco_ios', 'username': self.username, 'password': self.password, 'ip':self.ip } try: self.connect = ConnectHandler(**self.device) self.connect.enable() except (EOFError, NetMikoTimeoutException): print(u" 網絡設備%s: 無法連接!請確認該設備IPAddress是否可達!" %self.ip) return except (EOFError, NetMikoAuthenticationException): sprint(u" 網絡設備%s: 用戶名與密碼錯誤!請確認賬號與密碼!" %self.ip) return def disVersion(self): cmd = 'show version' print(self.connect.send_command(cmd)) self.connect.disconnect() def disInterface(self): cmd = 'show ip interface brief' print(self.connect.send_command(cmd)) self.connect.disconnect() def runComment(self): disfunc = int(input('pls input num: ')) if disfunc == 1: self.disVersion() if disfunc == 2: self.disInterface() if __name__ == '__main__': run = NWBackup() run.runComment()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。