您好,登錄后才能下訂單哦!
折騰了一天的裝飾器,貌似理解了其中的一點(diǎn)點(diǎn)...
#!/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" 網(wǎng)絡(luò)設(shè)備%s: 無法連接!請(qǐng)確認(rèn)該設(shè)備IPAddress是否可達(dá)!"%ip) return except (EOFError, NetMikoAuthenticationException): print(u" 網(wǎng)絡(luò)設(shè)備%s: 用戶名與密碼錯(cuò)誤!請(qǐng)確認(rèn)賬號(hào)與密碼!" %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"選項(xiàng)請(qǐng)輸入數(shù)字,如: 1、2") print(u"1. 查詢?cè)O(shè)備接口信息") print(u"2. 查詢?cè)O(shè)備版本信息") print("") runFunc = int(input(u'請(qǐng)輸入需要執(zhí)行命令的選項(xiàng): ')) 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()
運(yùn)執(zhí)行上面的代碼,運(yùn)行效果如下:
以下代碼用類也可以實(shí)現(xiàn)相一樣的結(jié)果,可以對(duì)比一下那個(gè)方便
#!/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" 網(wǎng)絡(luò)設(shè)備%s: 無法連接!請(qǐng)確認(rèn)該設(shè)備IPAddress是否可達(dá)!" %self.ip) return except (EOFError, NetMikoAuthenticationException): sprint(u" 網(wǎng)絡(luò)設(shè)備%s: 用戶名與密碼錯(cuò)誤!請(qǐng)確認(rèn)賬號(hào)與密碼!" %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()
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。