Search This Blog

Sunday 16 May 2021

Nornir Compliance Check

 Credits to IPvZero for this who posted the original solution which was modified to suit my needs : https://github.com/IPvZero/nornir-test-compliance/blob/master/comply.py

colorama==0.4.4
genie==21.4
netmiko==3.4.0
nornir==3.1.1
nornir-netmiko==0.1.1
nornir-utils==0.1.2
pyats==21.4

from nornir import InitNornir
from nornir_netmiko.tasks import netmiko_send_command, netmiko_send_config
from nornir_utils.plugins.functions import print_result, print_title
from nornir.core.exceptions import NornirExecutionError
from nornir.core.task import Task, Result
import getpass
import sys
import os
from colorama import Fore, Style
import threading
import ntp_check

nr = InitNornir(config_file="config.yml")

# to run this script use: "env $(gpg --decrypt encrypted.env.gpg) python3 compliance-nornir3-encrypted.py"
nr.inventory.defaults.username = os.getenv("DEFAULT_USERNAME")
nr.inventory.defaults.password = os.getenv("DEFAULT_PASSWORD")

LOCK = threading.Lock()

with open('compliance-cmds.txt''r'as f:
    filelines = f.readlines()

clear_command = "clear"
#os.system(clear_command)
def ntp_check(task):
    mylist=[]
    output = task.run(task=netmiko_send_command, command_string="show run"use_genie=False)
    for cmd in filelines:
        if not cmd in output.result:
            mylist.append(cmd)
        else:
            print(Fore.GREEN + Style.BRIGHT+ "*" * 80)
            print(Fore.GREEN + f"ALERT: {task.host} is compliant!")
            print(Fore.GREEN + "Well Done!")
    if not mylist:
        john = "blah-de-blah"
    else:
        LOCK.acquire()
        print(Fore.GREEN + Style.BRIGHT+ "*" * 80)
        print(Fore.RED + f"ALERT: {task.host} is not NTP compliant!")
        print(Fore.YELLOW + "The following commands are missing:")
        try:
            for items in mylist:
                print(items)
        finally:
            LOCK.release()
            
results = nr.run(task=ntp_check)

print_title("COMPLETED COMPLIANCE TEST")
#print_result(results)

No comments:

Post a Comment

Nornir Compliance Check