我将简单化,因为我对Python面向对象编程仍然不太满意。
ip = raw_input("Device ip: ")
# Ask for connection credentials
def get_credentials():
username = raw_input("Username: ")
password = None
while not password:
password = getpass()
password_verify = getpass('Retype your password: ')
if password != password_verify:
print ('Passwords do not match. Try again.')
password = None
return username, password
waiting_displaying = "."
connection = netmiko.ConnectHandler(ip, get_credentials.username, get_credentials.password, device_type='cisco_ios' )
基于上面列出的代码
我试图将用户名和密码的值从其局部变量传递到
ConnectHandler
模块中netmiko
方法的属性部分。
我在网上听说你可以传递返回的值但是因为我猜它们被存储为元组或字典键,所以看起来有点困难而且我不太确定如何去做它
记录:
getpass
是从名为getpass
。ConnectHandler
是从名为netmiko
。答案 0 :(得分:0)
使用collections.namedtuple。创建类似于元组的对象是一种简单快捷的方法,可以通过属性查找访问字段。
Credentials = collections.namedtuple('Credentials', ['username', 'password'], verbose=True)
def get_credentials():
...
return Credentials(username, password)
cc = get_credentials()
connection = netmiko.ConnectHandler(ip,cc.username, cc.password, device_type='cisco_ios' )
答案 1 :(得分:0)
创建一个包含数据的类:
class Credentials:
def __init__(self,username='',password=''):
self.username = username
self.password = password
def get_credentials(self):
# update self.username and self.password
self.username = ...
self.password = ...
cc = Credentials()
cc.get_credentials()
connection = netmiko.ConnectHandler(ip, cc.username, cc.password, device_type='cisco_ios' )