簡體   English   中英

Function 嘗試返回帶字典的元組時返回 None

[英]Function return None when trying to return a tuple with dictionary

我有一個 function 用於連接到網絡設備 (Netmiko)。 我正在從 .netmiko 捕獲 AuthenticationException,更改用戶信用並重試。

總機 function:

for round, device in zip(range(1, num_devices), devices):

    dev_class = d2c(device)
    print(f"Device {dev_class.Hostname}: {dev_class.MgmtIp}, {round} of {len(devices)}")
    devParsed = connectionMethods.Prep(dev_class, playVars)    
    services = connectionMethods.TestSSH(devParsed, user)

    print(services)


def TestSSH(device, user, notes_in = None, num_tries=0, timeout = 10):
    try:
        dict_out = {}
        notes = {'notes' : []}
        if notes_in:
            notes['notes'].append(notes_in)
            notes['notes'].append(f"Number of tries = {num_tries}")

        print(f"""************************************************\n"""
              f"""Connecting to device : {device.device.Hostname}\n"""
              f"""ip address : {device.device.MgmtIp}\n"""
              f"""Tried to connect before {num_tries} times.\n"""
              f"""Using {user.username} to connect\n"""
              f"""************************************************\n""")

        logging.basicConfig(filename='debug.log', level=logging.DEBUG)
        logger = logging.getLogger(f"netmiko")
        
        
        Conn = {'device_type':device.device.driver,
                 'ip': device.device.MgmtIp,
                 'username': user.username, 
                 'password': user.password,
                 'conn_timeout' : timeout,
        }

        pattern = re.compile(r'(server\s+)(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})')
        net_connect = ConnectHandler(**Conn)
        if not net_connect.check_enable_mode():
            net_connect.enable()
        
        for command in device.questions:
            output_list = []
            list_out = []
            for k, v in command.items():
                output = net_connect.send_command(v)
                print(f"""Output from device : 
                      {output}""")
                for line in output.splitlines():
                   result = pattern.search(line)
                   if result:
                      output_list.append(result.group(2))

                num_servers = len(output_list)
                print(f"Number of lines returned {num_servers}")
                if num_servers > 0:
                    for round, line in zip(range(1,num_servers + 1), output_list):
                        list_out.append(f"server{round} : {line}")
                    list_parsed = ','.join(list_out)
                    print(list_parsed)
                else: 
                    list_parsed = "No servers configured"
                
                dict_out.update({k : list_parsed})

    except NetmikoAuthenticationException as e:
        exception_type = type(e).__name__
        print(f"Error type = {exception_type}")
        if num_tries == 0:
            if input("Retry with a new token?:").lower() == "y": 
                retry_user = User()
                retry_user.GetToken()
                TestSSH(device, retry_user, notes_in= "admin login",num_tries=1, timeout=10)
            else:
                notes['notes'].append(f"{exception_type}, retries : {num_tries}")
                notes['notes'] = ','.join(notes.get('notes'))
                dict_out.update(notes)
                print(f""" Error from device {device.device.Hostname}:
                        {dict_out.get('notes')}""")
                
                return dict_out, 400
        else:
                notes['notes'].append(f"{exception_type}, retries : {num_tries}")
                notes['notes'] = ','.join(notes.get('notes'))
                dict_out.update(notes)
                print(dict_out)
                print(f""" Error from device {device.device.Hostname}:
                        {dict_out.get('notes')}""")
                print(type(dict_out))
                return dict_out, 401

讓我摸不着頭腦的是:如果 num_tries == 0 並且我選擇不嘗試另一個帳戶,則返回結果如我所料:

Retry with a new token?:n
 Error from device xxx.xxx.xxx:
                        NetmikoAuthenticationException, retries : 0
({'notes': 'NetmikoAuthenticationException, retries : 0'}, 400)

If num_tries is gt == 0: 

Error type = NetmikoAuthenticationException
{'notes': 'admin login,Number of tries = 1,NetmikoAuthenticationException, retries : 1'}
 Error from device xxx.xxx.xxx:
                        admin login,Number of tries = 1,NetmikoAuthenticationException, retries : 1
<class 'dict'>
None

當我在返回之前打印它時,我無法弄清楚返回的字典是 None 時它顯然不是。

歡迎任何有關如何解決問題的建議。 Python 版本 Python 3.9.6

Br, Heikki

我希望產生:

({'notes': 'NetmikoAuthenticationException, retries : 1'}, 401)

您在此處打印None : print(services)的原因是因為您還從其內部調用TestSSH()並且默認情況下 function 從那里退出 function。 也就是像python在function的最后給你寫了一個return None

您可以自己添加退貨,但我不知道這是否有幫助:

return TestSSH(device, retry_user, notes_in= "admin login",num_tries=1, timeout=10)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM