示例#1
0
def DiffinRunConfig(
):  # This function will check for changes in the config periodically
    global RunconfigDirPath
    for dir in Dirlist:
        filepath = RunconfigDirPath + '\\' + dir
        list_of_files = glob.glob(
            filepath + "/*run.txt"
        )  ## This will return type list of all files ending with run.txt
        sortfilelist = sorted(
            list_of_files,
            key=os.path.getctime)  ## Sorting files as per creation date
        try:
            oldfile = sortfilelist[-2]
            newfile = sortfilelist[-1]
            #    ignorefile = "ignore.txt"
            #    Diff = diffios.Compare(oldfile, newfile, ignorefile) ## Later will add ignore.txt to ignore irrelevant changes
            Diff = diffios.Compare(oldfile, newfile)
            with open(filepath + '\\' + 'Difference.txt', 'w+') as diffile:
                print("Running config difference between {} and {}".format(
                    newfile.split('\\')[-1],
                    oldfile.split('\\')[-1]),
                      file=diffile)
                print(Diff.delta(), file=diffile)
                print('_' * 40, file=diffile)
            #ignorefile.close()
        except IndexError:
            print('Not much files to compare')
        else:
            print("Difference Output saved in the designated folders")
示例#2
0
def main():
    ### Get the config files saved from getconfig function ###
    file_list = []
    dir_path = os.path.dirname(os.path.realpath(__file__))
    lis = os.listdir(dir_path)
    for i in range(1, 5):
        for item in lis:
            if "R" + str(i) in item:
                file_list.append(item)

    ### SSH connection to routers ###
    if os.path.isfile('sshInfo.json'):
        fh = open('sshInfo.json', 'r')
        ssh_data = json.load(fh)
        print(ssh_data)
        for items in file_list:
            rout = ["R1", "R2", "R3", "R4"]
            for item in rout:
                if item in items:
                    #print(item + ":" + items + " " + "yass")
                    driv = get_network_driver('ios')
                    iosv = driv(ssh_data[item]["hostname"],
                                ssh_data[item]["username"],
                                ssh_data[item]["password"])
                    iosv.open()
                    fh = open('config.txt', 'w')
                    out = str(iosv.get_config())
                    #for k,v in out.items():
                    #fh.write(k + ":" + v)
                    fh.write(out)
                    fh.close()
                    diff = diffios.Compare('config.txt', items)
                    print(diff.pprint_missing())
                    iosv.close()
示例#3
0
def compare_config(precheck_file, postcheck_file, host_ip):
    '''

    This section of code is used to compare configuration before and after change.
    Post comparision it sill share output with listed changes.

    '''
    diff_file = os.path.join(
        output_dir, host_ip + "_config_diff_file_" +
        time.strftime("%Y%m%d-%H%M%S") + "_.txt")
    diff_config = diffios.Compare(precheck_file, postcheck_file)
    with open(diff_file, "a+") as diff:
        diff.writelines(diff_config.delta())
def get_config_diff(template, config, ignore=None):
    """Get inconsistency between device running config and template."""

    if not ignore:
        ignore = [
            "Building configuration",
            "Current configuration",
            "NVRAM config last updated",
            "Last configuration change",
        ]

    diff = diffios.Compare(template, config, ignore)

    # Get lines that exist in template only
    missing_lines = diff.missing()

    return missing_lines
示例#5
0
def CurrentDif(
):  #This function will check changes in the config comparing last saved file via this script and the current device config
    input1 = input(
        "Enter the Device Name for which you want to check the changes made as compared to Last Run: \n"
    )
    randomno = 0
    for dir in Dirlist:
        if dir.lower() == input1.lower(
        ):  ## .lower() helps comparing string ignoring case sensitivity
            randomno = 1
            filepath = RunconfigDirPath + '\\' + dir
            list_of_files = glob.glob(filepath + "/*run.txt")
            sortfilelist = sorted(list_of_files, key=os.path.getctime)
            lastfile = sortfilelist[-1]  ### This would be the lastfile

            for device in Ciscodevicelist:
                if device['Name'].lower() == input1.lower():
                    IP = (device['IP'])
                    netmikoobj = {
                        'device_type': 'cisco_ios',
                        'host': IP,
                        'username': Username,
                        'password': Pwd
                    }
                    latestoutput = CommonFunc.devicelogin_1(
                        netmikoobj,
                        ['terminal length 0', 'show running-config'])
                    if latestoutput == 'None':
                        sys.exit()
                    with open('CurrentR.txt', 'w+') as currentrun:
                        print(latestoutput, file=currentrun)
                    Diff = diffios.Compare(lastfile, 'CurrentR.txt')
                    print(
                        "Below is the difference between Current Config and config copied on {}"
                        .format(lastfile.split('\\')[-1]))
                    print(Diff.delta())

    if randomno == 0:
        print(
            "Couldnt find the device data, Kindly check if Device Name is correct or its data is backed up via this Script"
        )
示例#6
0
                os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import diffios

IGNORE_FILE = os.path.join(os.getcwd(), "ignores.txt")
COMPARISON_DIR = os.path.join(os.getcwd(), "configs", "comparisons")
BASELINE_FILE = os.path.join(os.getcwd(), "configs", "baselines",
                             "baseline.txt")

output = os.path.join(os.getcwd(), "diffs.csv")

with open(output, 'w') as csvfile:
    csvwriter = csv.writer(csvfile, lineterminator='\n')
    csvwriter.writerow(["Comparison", "Baseline", "Additional", "Missing"])
    files = sorted(os.listdir(COMPARISON_DIR))
    num_files = len(files)
    for i, fin in enumerate(files, 1):
        #  print("diffios: {:>3}/{} Processing: {}".format(i, num_files, fin),
        #        end="\r")
        comparison_file = os.path.join(COMPARISON_DIR, fin)
        diff = diffios.Compare(BASELINE_FILE, comparison_file, IGNORE_FILE)
        csvwriter.writerow([
            fin,
            os.path.basename(BASELINE_FILE),
            diff.pprint_additional(),
            diff.pprint_missing()
        ])
        print("diffios: {} ({}/{})".format(fin, i, num_files))
        print(diff.delta())
    print("diffios: Report: {}".format(output))
示例#7
0
#!/usr/bin/python

from os import system
import sys
import diffios

base = sys.argv[1]
compare = sys.argv[2]

if base == "running-config":
    system("Cli -p 15 -c 'show run > flash:showrun.conf'")
    baseline = "/mnt/flash/showrun.conf"
elif base == "startup-config":
    baseline = "/mnt/flash/startup-config"
else:
    baseline = "/mnt/flash/.checkpoints/" + base

comparison = "/mnt/flash/.checkpoints/" + compare

diff = diffios.Compare(baseline, comparison)

print(diff.delta())
示例#8
0
T = today.strftime("%Y%m%d")
Y = yesterday.strftime("%Y%m%d")

## define file cisco config with timestamp
baseline1 = '/PATH/TO/FILE/SWITCH-ANSIBLE_{}.txt'.format(Y, Y)
comparison1 = '/PATH/TO/FILE/SWITCH-ANSIBLE_{}.txt'.format(T, T)
baseline2 = '/PATH/TO/FILE/ROUTER-ANSIBLE_{}.txt'.format(Y, Y)
comparison2 = '/PATH/TO/FILE/ROUTER-ANSIBLE_{}.txt'.format(T, T)

## write to file diff
DiffToday = '/PATH/TO/FILE/diff_{}.txt'.format(T)
file = open(DiffToday, "w")

## compare switch config today and yesterday with error handling
if os.path.isfile(baseline1) and os.path.isfile(comparison1):
    diff1 = diffios.Compare(baseline1, comparison1)
    file.write("\n Comparison SWITCH-ANSIBLE Today and Yesterday \n")
    file.write(diff1.delta())
    file.write("\n \n")
else:
    file.write("DC-SWITCH-ANSIBLE Backup Config File doesn't exist \n \n")

## compare router config today and yesterday with error handling
if os.path.isfile(baseline2) and os.path.isfile(comparison2):
    diff2 = diffios.Compare(baseline2, comparison2)
    file.write("Comparison ROUTER-ANSIBLE Today and Yesterday \n")
    file.write(diff2.delta())
    file.write("\n \n")
else:
    file.write("ROUTER-ANSIBLE Backup Config File doesn't existi \n \n")
#CCIE/CCSI:Yasser Ramzy Auda
#https://www.facebook.com/yasser.auda
#https://www.linkedin.com/in/yasserauda/
#https://github.com/YasserAuda/PythonForNetowrk-Cisco

#pip install diffios

#diffios is a Python library that provides a way to compare Cisco IOS
#configurations against a baseline template, and generate an output
#detailing the differences between them.

#https://github.com/robphoenix/diffios

import diffios
baseline = "R1.txt"
comparison = "R2.txt"
ignore = "ignore.txt"

diff = diffios.Compare(baseline, comparison, ignore)
print(diff.delta())