Closing connections

What is the best way to gracefully close a Netmiko connection? I’m doing some testing with both netmiko_send_command and netmiko_send_config and I want to close out connections after each batch of commands sent. In native Netmiko I would just object.disconnect() at the end of the function, I can’t find the equivalent attribute in the docs. Well, I found the close() function in the plugin, but I’m not real sure how to implement it in the way I need.

Thanks in advance.

image

The above code seems to work for this. Verified by checking ‘show user’ on an ios device before and after multiple executions.

1 Like

For anyone coming along later, the comment nornir_show() snippet describes what the function WILL do. It is not finished in this snippet. Just to save some confusion.

You have information about it here: https://nornir.readthedocs.io/en/stable/howto/handling_connections.html

for some reason we don’t have context manager in the tutorial anywhere
@JCox0511
the easiest way to handle connections is:

with InitNornir(...) as nr:
   # your tasks

Nornir automatically opens connections for you and with the context manager (with block) at the end of the block, all open connections are going to be closed for you.

2 Likes

I like it, that cleans it up nicely. Thanks.

The one caveat to this is if you inject any values into the inventory/defaults/config, you will lose those values each time the context manager opens again. For example, if you assign default credentials by injecting them during your runtime rather than environment variables, then when the context manager opens again, it will re-initialize the Nornir object and those dynamically inserted credentials are lost. As a workaround to this, you could create a helper function to re-insert those attributes and call it each time you use the context manager. I think the code is still probably much cleaner this way and connections are still closed automatically.

1 Like

I’d would use a context manager only once

would probably be nice to add a note in the howto I linked.