折腾了一天的装饰器,貌似理解了其中的一点点...
#!/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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。