[python]Checking whether the hosts in inventory are alive with Nornir

Nornir has a tcp_ping function that can be used to test connections within the inventory file.

You can check one or multiple ports, you can also specify the hosts of your choice

So let’s see how can this be used.

Check if a port is live for hosts in inventory

This is my yaml inventory file:

mgmt:
  hostname: 192.168.100.101
  password: ''
  platform: cisco_ios
  port: '22'
  username: ''
R2:
  hostname: 192.168.100.102
  password: ''
  platform: cisco_ios
  port: '22'
  username: ''
R3:
  hostname: 192.168.100.103
  password: ''
  platform: cisco_ios
  port: '22'
  username: ''
R4:
  hostname: 192.168.100.104
  password: ''
  platform: cisco_ios
  port: '22'
  username: ''
R5:
  hostname: 192.168.100.105
  password: ''
  platform: cisco_ios
  port: '22'
  username: ''

So here I can test if port 22 is alive for all hosts, if no hosts are specified the hosts will be based according to specified yaml host file.

from nornir.plugins.tasks.networking import tcp_ping
from nornir import InitNornir
from os.path import join
from pathlib import Path

host_file = join(Path(__file__).parent.parent.absolute(), "network", "inventory", "cisco_ios.yaml")

with InitNornir(
        inventory={
            "plugin": "nornir.plugins.inventory.simple.SimpleInventory",
            "options":
                {
                    "host_file": host_file
                }
        }
) as nr:
    result = nr.run(task=tcp_ping,
                    ports=22)
    for k, v in result.items():
        print(
            {
                k: v.result
            }
        )

The returned result will be like this:
nor47

Check if multiple ports alive in hosts

tcp_ping ports argument that accepts a list of integers, hence I change my argument to this [x for x in range(22,26)].

from nornir.plugins.tasks.networking import tcp_ping
from nornir import InitNornir
from os.path import join
from pathlib import Path

host_file = join(Path(__file__).parent.parent.absolute(), "network", "inventory", "cisco_ios.yaml")

with InitNornir(
        inventory={
            "plugin": "nornir.plugins.inventory.simple.SimpleInventory",
            "options":
                {
                    "host_file": host_file
                }
        }
) as nr:
    result = nr.run(task=tcp_ping,
                    ports=[x for x in range(22,26)])
    for k, v in result.items():
        print(
            {
                k: v.result
            }
        )

The result will be like this:
nor49

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s