Python:装饰器的小例子
折腾了一天的装饰器,貌似理解了其中的一点点...
专注于为中小企业提供成都做网站、网站制作服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业长岛免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
#!/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()
标题名称:Python:装饰器的小例子
转载来于:http://www.jxjierui.cn/article/gchdjp.html


咨询
建站咨询
