Esempio n. 1
0
def jsnapy_post(task):
    host_check_yml = output_dir + task.host.name + '_check.yml'
    with open(host_check_yml, 'r') as f:
        host_check_resutl = f.read()
    js = SnapAdmin()
    config_host = config_data.format(task.host.hostname, task.host.username,
                                     task.host.password, host_check_resutl)
    js.snap(config_host, "post")
    snapchk = js.check(config_host, "pre", "post")
    result_output = '{}{}_{}_result.txt'
    for val in snapchk:
        with open(result_output.format(output_dir, task.host.name, dates),
                  'w') as f:
            f.write(json.dumps(dict(val.test_details), indent=4))
Esempio n. 2
0
    def post_compare(self):
        """ Run post check and gather output """
        # Setup a memory buffer to capture logging messages from jsnapy
        jsnapy_log = logging.handlers.MemoryHandler(1024 * 10, logging.DEBUG)
        jsnapy_log.setLevel(logging.DEBUG)
        log = logging.getLogger()
        log.setLevel(logging.DEBUG)
        debug_format = logging.Formatter("%(message)")
        jsnapy_log.setFormatter(debug_format)
        log.addHandler(jsnapy_log)

        # Run jsnapy check on pre and post snapshots
        js = SnapAdmin()
        self.result = js.check(self.template, pre_file="pre", post_file="post")

        # Gather output from buffer
        post_log = []
        for line in jsnapy_log.buffer:
            post_log.append(str(line.getMessage()))
        self.data = format_html.formatting(post_log)
def main():

    js = SnapAdmin()

    config_file = "infra.yaml"
    js.snap(config_file, "module_snap1")
    js.snap(config_file, "module_snap1")
    chk = js.check(config_file, "module_snap1", "module_snap1")

    for check in chk:
        print "Tested on", check.device
        print "Final result: ", check.result
        print "Total passed: ", check.no_passed
        print "Total failed:", check.no_failed
        #pprint(dict(check.test_details))

    if (check.result == "Failed"):
        print("The snapshot verification has failed")

    else:
        print("The snapshot verification was successful")

    pprint(dict(check))
Esempio n. 4
0
def invokeTests(vmanme):

    js = SnapAdmin()

    helpers = Helpers()

    config_file = """
    hosts:
    - device: 192.168.122.9
      username: ubuntu
    tests:
    - test_diff.yml
    """

    #js.snap(config_file, "pre")
    js.snap(config_file, "post")
    chk = js.check(config_file, "pre", "post")

    '''
    file_name = "/home/ubuntu/Evolved_Campus_Core_Automation/Inventory"
    with open(file_name) as f:
        content = f.read()
        campuses = re.findall('\[(.*?)\]',content)

    campuses_info = {}
    for campus in campuses:
        if "children" in campus:
            campus_id = campus.rsplit(":",1)[0]
            campuses_info.update({campus_id: {'leaf': [],'spine':[]}})
    for campus in campuses:
        leaf_count = 0
        spine_count = 0
        campus_id = campus.rsplit("-")[1]
        if not "children"in campus:
            if "leaf" in campus:
                data_loader = DataLoader()
                inventory = InventoryManager(loader = data_loader,
                                            sources=[file_name])
                lst = inventory.get_groups_dict()[campus]
                for ls in lst:
                    campuses_info['campus-' + campus_id]['leaf'].append(ls)
            elif "spine" in campus:
                data_loader = DataLoader()
                inventory = InventoryManager(loader = data_loader,
                                            sources=[file_name])
                lst = inventory.get_groups_dict()[campus]
                for ls in lst:
                    campuses_info['campus-' + campus_id]['spine'].append(ls)

    '''
    spine_leaf_info = {}
    '''
    for campus in campuses_info:
        for leaf_dev in campuses_info[campus]["leaf"]:
            spine_leaf_info.update({leaf_dev: campuses_info[campus]["spine"]})
    '''

    devip = ""
    failed = 0
    test_name = ""
    for check in chk:
        devip = check.device
        failed = check.no_failed
        if not not check.test_results.keys():
            test_name = check.test_results.keys()[0].replace(' ','_')

    ae_id = ""
    dev = helpers.device_connect(devip)
    dev.open()
    data = dev.rpc.get_config(options={'format':'json'})
    for ints in data['configuration']['interfaces']['interface']:
        if "ae" in ints['name']:
            ae_id = ints['name']
    dev.close()

    pre_file = '/home/ubuntu/jsnapy/snapshots/' + devip + '_pre_' + test_name + '.xml'
    post_file = '/home/ubuntu/jsnapy/snapshots/' + devip + '_post_' + test_name + '.xml'

    dict = {}
    if failed != 0:
        with open(pre_file, 'r') as hosts0:
            with open(post_file, 'r') as hosts1:
                diff = difflib.unified_diff(
                    hosts0.readlines(),
                    hosts1.readlines(),
                    fromfile='hosts0',
                    tofile='hosts1',
                    n=0,
                )
                lines = list(diff)[2:]
        print lines
        added = [line[1:] for line in lines if line[0] == '+']
        additions = ""
        for line in added:
            additions += line
        print 'additions'
        vlan_text = ""
        if additions:
            tree = xml.etree.ElementTree.fromstring(additions)
            print tree
            for vlan in tree.findall('l2ng-l2rtb-vlan-name'):
                text = vlan.text
                vlan_text = text.split("vlan")[1]
                print vlan_text

            dict = {'vqfx3': {'vlanid':vlan_text}}
            template_file = '/home/ubuntu/Evolved_Campus_Core_Automation/Config/QFX_vlan_leaf_addition.conf'
            helpers.load_template_config(devip,"spine",dict,template_file)

            '''
            print spine_leaf_info
            for spine_ip in spine_leaf_info[devip]:
                template_file = '/home/ubuntu/Evolved_Campus_Core_Automation/Config/QFX_vlan_spine_addition.conf'
                #helpers.load_template_config(spine_ip,"spine",dict,template_file)
            '''

    if failed != 0:
        with open(post_file) as f:
            lines = f.readlines()
            lines1 = ""
            for line in lines:
                lines1 += line
            with open(pre_file, "w") as f1:
                f1.writelines(lines1)
js.snap(config_file, "pre")
# jsnapy closed the connection after the snapshot.

# this is where you are supposed to apply your configuration changes

# taking second snapshot using jsnapy
# Performing function similar to --snap
print "taking second snapshots using jsnapy"
js.snap(config_file, "post")
# jsnapy closed the connection after the snapshot.

# Performing function similar to --check
# comparing first and second snapshots using jsnapy. and printing the result.
# sending slack notifications
print "comparing first and second snapshots using jsnapy"
chk = js.check(config_file, "pre", "post")
slack = Slacker(
    'xoxp-89396208643-89446660672-130436631236-426fdc2e3aeb3afc1af0acba9373a3ac'
)
for check in chk:
    #    print "Tested on", check.device
    #    print "Final result: ", check.result
    #    print "Total passed: ", check.no_passed
    #    print "Total failed:", check.no_failed
    #    print check.test_details
    #    pprint(dict(check.test_details))
    slack.chat.post_message('#general',
                            "check.py with device " + check.device +
                            ". Tests result is " + str(check.result),
                            username='******')
Esempio n. 6
0
def myprint(str):

    print(time.strftime(" %H:%M:%S", time.gmtime()) + "  " + str)


host = raw_input('hostname: ')
user = raw_input('username: '******'password: '******'Unable to connect: ', error
    exit()
dev.timeout = 2500

js = SnapAdmin()
config_file = "junos-upgrade.yml"

myprint("waiting 10 seconds before taking post snapshot....")
time.sleep(10)
myprint("gathering snapshot after upgrade....")
snapvalue = js.snap(config_file, "post", dev=dev)

print
myprint("Comparing pre and post snapshots")
snapvalue = js.check(config_file, "pre", "post", dev=dev)
Esempio n. 7
0
import pprint
from jnpr.jsnapy import SnapAdmin
from jnpr.junos import Device

CONFIG_FILE = 'test_show_default_route.yml'
PRE_SNAP = 'pre_show_route_test.xml'
POST_SNAP = 'post_show_route_test.xml'

TESTS = {'tests': [CONFIG_FILE]}

if __name__ == "__main__":
    device = Device(host='example.com', user='******', passwd='123456')

    snap = SnapAdmin()
    r = snap.check(TESTS, PRE_SNAP, POST_SNAP, device)
    pprint.pprint(r[0].test_results)
Esempio n. 8
0
### Performing function similar to --check in command line ###
from jnpr.jsnapy import SnapAdmin
from pprint import pprint
from jnpr.junos import Device

js = SnapAdmin()

config_file = "/etc/jsnapy/testfiles/config_check.yml"
js.snap(config_file, "pre")
js.snap(config_file, "post")
chk = js.check(config_file, "pre", "post")

for check in chk:
    print "Tested on", check.device
    print "Final result: ", check.result
    print "Total passed: ", check.no_passed
    print "Total failed:", check.no_failed
    print check.test_details
    pprint(dict(check.test_details))