简体   繁体   中英

Netmiko session time Python

Is there a way to login with Netmiko to a Cisco device and stay logged in? I have a Python script that should connect every 5 seconds to a Cisco device, but it would be better to login once and stay logged in, and just pull the data from the Cisco device by sending commands via script.

Thank you in advance

Are you aware of the keepalive parameter? You should also pay attention to the timeout in the device and allow for a noise margin.

To everyone having this problem, the thing is that after the python script is done it will automatically disconnect from the Cisco device even if you did not put disconnect command for Netmiko.

So, to the solution to this is to always stay connected is:

Connect to each of your network devices before you create a loop:

asafw1 = {
    "host": "10.0.1.1",
    "device_type": "cisco_ios",
    "username": "user",
    "password": "password",
}
asafw2 = {
    "host": "10.2.1.1",
    "device_type": "cisco_ios",
    "username": "user",
    "password": "password",
}

conn1 = ConnectHandler(**asafw1)
conn2 = ConnectHandler(**asafw2)

Then you define your function and you pass conn argument into that function:

def update_user_info_function(conn):

### Connection to ASA via Netmiko module and Connection Handler function ###
asa_output = conn.send_command("show version")
print(asa_output)

Now you call your function and use the above configured conn1 and conn2 as arguments:

while True:
    update_user_info_function(conn1)
    update_user_info_function(conn2)
    ### Wait 1 seconds before you go through the loop again ###
    time.sleep(1)

So, your networking script will always run, and you will always be connected to your device. This is very helpful if you have a radius server, and all of your devices are pointed to that server, like this you will connect only once to your device, stay connected and pull data from that unit. Thus, you will not connect to that device every time to pull data, meaning that you will not utilize CPU that much, and you will not generate many lines of log on the radius server.

This solution was very helpful to us, because we are trying to get VPN data from the Cisco device and send that data to the mysql. Using this, we can pull data from the Cisco device every second, and send that data to the mysql and have it stored there for the web view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM