def check_compliance(hostname, test_file): opts = salt.config.master_config('/etc/salt/master') runner = salt.runner.RunnerClient(opts) pillar = runner.cmd('pillar.show_pillar', [hostname]) config_file_object = { "hosts": [ { "device": pillar['proxy']['host'], "username": pillar['proxy']['username'], "passwd": pillar['proxy']['passwd'] } ], "tests": [ test_file ] } config_file = yaml.dump(config_file_object) js = SnapAdmin() snapcheck_output = js.snapcheck(config_file, "automatic_snapshot_from_saltstack") json_output = {} for item in snapcheck_output: json_output = { 'jsnapy_device_name': hostname, 'jsnapy_device_ip': item.device, 'jsnapy_result': item.result, 'jsnapy_nbr_passed': item.no_passed, 'jsnapy_nbr_failed': item.no_failed, 'jsnapy_test_file': test_file } if json_output['jsnapy_result'] == 'Failed': caller = salt.client.LocalClient() caller.cmd(hostname, 'event.send', ['jnpr/compliance/failed'], kwarg={'result': json_output}) return json_output
def audit_config(*args, **kvargs): CONF_DATA = """ tests: - test_telnet.yml mail: /etc/jsnapy/send_mail.yml hosts: """ vMX_1_DATA = """ - device: 10.254.0.41 username: lab passwd: lab123 """ vMX_2_DATA = """ - device: 10.254.0.42 username: lab passwd: lab123 """ if "device" in kvargs: if kvargs["device"] == "vMX-1": CONF_DATA += vMX_1_DATA if kvargs["device"] == "vMX-2": CONF_DATA += vMX_2_DATA else: # possibly called by salt-run CONF_DATA += (vMX_1_DATA + vMX_2_DATA) snapadmin = SnapAdmin() result = snapadmin.snapcheck(CONF_DATA, "pre")
def config_verification(services, args): """Perform config verification with JSNAPy """ def get_test_text(name, port): return """ --- test_app_%s: - rpc: get-config - item: id: ./name xpath: 'applications/application[name="k8s%s"]' tests: - is-equal: destination-port, %s info: "Test Succeeded!!, destination-port is <{{post['destination-port']}}>" err: "Test Failed!!!, destination-port is <{{post['destination-port']}}>" """ % (name, name, port) jsnapy_config = { "hosts": [{ "device": "127.0.0.1", "username": "******", "passwd": "Juniper", "port": args.vsrx_port }], "tests": [] } for service in services: # Create test file for this service test_filename = "scripts/jsnapytest_%s.yaml" % service["name"] with open(test_filename, 'w') as testfile: testfile.write(get_test_text(service["name"], service["port"])) # Add reference for this test file to config jsnapy_config["tests"].append(test_filename) # Write config file to disk with open('scripts/jsnapyconfig.yaml', 'w') as configfile: yaml.dump(jsnapy_config, configfile, default_flow_style=False) # Retrieve instant snapshot and run tests on result js = SnapAdmin() chk = js.snapcheck('scripts/jsnapyconfig.yaml') # Ensure all tests passed for check in chk: assert check.result == "Passed"
### performing function similar to --snapcheck option 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_single_snapcheck.yml" snapvalue = js.snapcheck(config_file, "snap") for snapcheck in snapvalue: print "\n -----------snapcheck----------" print "Tested on", snapcheck.device print "Final result: ", snapcheck.result print "Total passed: ", snapcheck.no_passed print "Total failed:", snapcheck.no_failed pprint(dict(snapcheck.test_details))
# performing function similar to --snapcheck option in command line # usage of jsnapy python library without pyez. from jnpr.jsnapy import SnapAdmin # instanciate the class SnapAdmin js = SnapAdmin() # the variable config_file refers to the jsnapy configuration file config_file = "cfg_file_snapcheck_bgp_states.yml" # Performing function similar to --snapcheck # taking a snapshot (called snap_from_python) and comparing it against predefined criteria snapvalue = js.snapcheck(config_file, "snap_from_python") # jsnapy closed the connection after the snapshot. # printing the result print "comparing snapshots against predefined criteria using jsnapy" for snapcheck in snapvalue: # print "\n -----------snapcheck----------" # print "Tested on", snapcheck.device # print "Final result: ", snapcheck.result # print "Total passed: ", snapcheck.no_passed # print "Total failed:", snapcheck.no_failed # pprint(dict(snapcheck.test_details)) if snapcheck.no_failed != 0: print "this device failed some tests: " + snapcheck.device
#! /Library/Frameworks/Python.framework/Versions/2.7/bin/python ### Example showing how to pass yaml data in same file ### from jnpr.jsnapy import SnapAdmin from pprint import pprint from jnpr.junos import Device js = SnapAdmin() config_data = """ hosts: - device: 172.16.226.10 username : silvia passwd: SilviaMurgescu tests: - test_exists.yml - test_contains.yml - test_is_equal.yml """ snapchk = js.snapcheck(config_data, "pre") for val in snapchk: print "Tested on", val.device print "Final result: ", val.result print "Total passed: ", val.no_passed print "Total failed:", val.no_failed pprint(dict(val.test_details))
### Example showing how to pass yaml data in same file ### from jnpr.jsnapy import SnapAdmin from pprint import pprint from jnpr.junos import Device js = SnapAdmin() config_data = """ hosts: - device: 10.209.16.204 username : demo passwd: demo123 tests: - test_exists.yml - test_contains.yml - test_is_equal.yml """ snapchk = js.snapcheck(config_data, "pre") for val in snapchk: print "Tested on", val.device print "Final result: ", val.result print "Total passed: ", val.no_passed print "Total failed:", val.no_failed pprint(dict(val.test_details))
""" js = SnapAdmin() my_devices_list = ["172.30.179.74", "172.30.179.73", "172.30.179.95"] for item in my_devices_list: print "opening a connection to a junos device using pyez" dev_obj = Device(host=item, user='******', password='******') dev_obj.open() cfg = Config(dev_obj) print "configuring the device " + dev_obj.facts["hostname"] cfg.load("set system login message hello", format='set') print "here's the configuring details pushed with pyez" cfg.pdiff() print "commiting the configuration change " if cfg.commit() == True: print "commit succeed" else: print "commit failed" print "auditing the device " + dev_obj.facts["hostname"] + " using jsnapy" snapchk = js.snapcheck(config_data, "snap", dev=dev_obj) print "rollback the device " + dev_obj.facts["hostname"] + " using pyez" cfg.rollback(rb_id=1) cfg.commit() dev_obj.close() for val in snapchk: print "Tested on", val.device print "Final result: ", val.result print "Total passed: ", val.no_passed print "Total failed:", val.no_failed
class Router: def __init__(self, hostname, model, ipaddress, username, password): self.hostname = hostname self.model = model self.username = username self.password = password self.ipaddress = ipaddress self.device = Device(host=ipaddress, user=username, password=password) self.snap = SnapAdmin() def open(self): self.device.open() self.device.bind(cu=Config) def lock(self): self.device.cu.lock() def unlock(self): self.device.cu.unlock() def close(self): self.device.close() def commit(self): return self.device.cu.commit() def rollback(self): return self.device.cu.rollback() def diff_config(self): if self.device.cu.diff(): message = self.device.cu.diff() else: message = '' return message def commit_check(self): return self.device.cu.commit_check() def load_config(self, operation_name, operation_param=None): set_result = False message = '' if operation_name == 'set_add_interface': template_filename = './set_templates/add_interface.jinja2' tamplate_param = operation_param elif operation_name == 'set_add_bgp_neighbor': template_filename = './set_templates/add_bgp_neighbor.jinja2' tamplate_param = operation_param elif operation_name == 'set_add_bgp_policy_external': template_filename =\ './set_templates/add_bgp_policy_external.jinja2' tamplate_param = operation_param else: pass config_txt = self.generate_from_jinja2(template_filename, tamplate_param) self.device.cu.load(template_path=template_filename, template_vars=tamplate_param, format="text", merge=True) message = config_txt set_result = True return set_result, message def nwtest(self, operation_name, operation_param=None): nwtest_result = False message = '' template_filename = '' if operation_name == 'nwtest_hostname': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = {'hostname': self.hostname} nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ self.hostname +\ '.yml' elif operation_name == 'nwtest_model': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = {'model': self.model} nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ self.hostname +\ '.yml' elif operation_name == 'nwtest_interface': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = operation_param nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ operation_param['interface_name'].replace('/', '-') + '_' +\ operation_param['interface_status'] +\ '.yml' elif operation_name == 'nwtest_bgp_neighbor': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = operation_param nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ operation_param['neighbor_address_ipv4'].replace('.', '-') + '_' +\ operation_param['neighbor_status'] +\ '.yml' elif operation_name == 'nwtest_bgp_received_route': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = operation_param nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ operation_param['neighbor_address_ipv4'].replace('.', '-') + '_' +\ operation_param['received_route_address_ipv4'].replace('.', '-') +\ '.yml' elif operation_name == 'nwtest_bgp_advertised_route': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = operation_param nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ operation_param['neighbor_address_ipv4'].replace('.', '-') + '_' +\ operation_param['advertised_route_address_ipv4'].replace('.', '-') +\ '.yml' elif operation_name == 'nwtest_ping': template_filename =\ './nwtest_templates/%s.jinja2' % (operation_name) tamplate_param = operation_param nwtest_filename =\ './nwtests/' +\ operation_name + '_' +\ operation_param['target_ipaddress'].replace('.', '-') +\ '.yml' else: pass self.generate_nwtestfile(template_filename=template_filename, template_param=tamplate_param, nwtest_filename=nwtest_filename) jsnapy_conf = 'nwtests:' + '\n' +\ ' - %s' % (nwtest_filename) snapcheck_dict = self.snap.snapcheck(data=jsnapy_conf, dev=self.device) for snapcheck in snapcheck_dict: if snapcheck.result == 'Passed': nwtest_result = True if operation_name == 'nwtest_bgp_received_route': expected_value = '%s/%s' % ( operation_param['received_route_address_ipv4'], operation_param['received_route_subnet_ipv4']) acutual_value =\ snapcheck.test_details.values()[0][0]['passed'][0]['pre'].keys()[0] elif operation_name == 'nwtest_bgp_advertised_route': expected_value = '%s/%s' % ( operation_param['advertised_route_address_ipv4'], operation_param['advertised_route_subnet_ipv4']) acutual_value =\ snapcheck.test_details.values()[0][0]['passed'][0]['pre'].keys()[0] else: expected_value =\ snapcheck.test_details.values()[0][0]['expected_node_value'] acutual_value =\ snapcheck.test_details.values()[0][0]['passed'][0]['actual_node_value'] message =\ 'nwtest file : %s\n' % nwtest_filename +\ 'expected value : %s\n' % (expected_value) +\ 'acutual value : %s' % (acutual_value) elif snapcheck.result == 'Failed': nwtest_result = False if operation_name == 'nwtest_bgp_received_route': expected_value = '%s/%s' % ( operation_param['received_route_address_ipv4'], operation_param['received_route_subnet_ipv4']) acutual_value = 'None' elif operation_name == 'nwtest_bgp_advertised_route': expected_value = '%s/%s' % ( operation_param['advertised_route_address_ipv4'], operation_param['advertised_route_subnet_ipv4']) acutual_value = 'None' else: expected_value =\ snapcheck.test_details.values()[0][0]['expected_node_value'] acutual_value =\ snapcheck.test_details.values()[0][0]['failed'][0]['actual_node_value'] message = 'nwtest file : %s\n' % nwtest_filename +\ 'expected value : %s\n' % (expected_value) +\ 'acutual value : %s' % (acutual_value) return nwtest_result, message def generate_nwtestfile(self, template_filename, template_param, nwtest_filename): nwtest_yml = self.generate_from_jinja2(template_filename, template_param) # write nwtest file (YAML format) with open(nwtest_filename, 'w') as f: f.write(nwtest_yml) def generate_from_jinja2(self, template_filename, template_param): # read template file (jinja2 format) with open(template_filename, 'r') as f: template_jinja2 = f.read() # generate nwtest file from template file return Environment().from_string(template_jinja2).render( template_param)
from jnpr.jsnapy import SnapAdmin from pprint import pprint # instanciate the class SnapAdmin js = SnapAdmin() # pass data in same file instead of using an external configuration file config_data = """ hosts: - include: devices.yml group: EX4300 tests: - test_file_snapcheck_bgp_states.yml """ # Performing function similar to --snapcheck # taking a snapshot (called snap) and comparing it against predefined criteria snapchk = js.snapcheck(config_data, "snap") # jsnapy closed the connection after the snapshot. # printing the result. for val in snapchk: print "Tested on", val.device print "Final result: ", val.result print "Total passed: ", val.no_passed print "Total failed:", val.no_failed pprint(dict(val.test_details))
from jnpr.jsnapy import SnapAdmin from pprint import pprint # instanciate the class SnapAdmin js = SnapAdmin() # the variable config_file refers to the jsnapy configuration file config_file = "cfg_file_snapcheck_bgp_states.yml" # taking a snapshot using jsnapy # Performing function similar to --snap print "taking snapshots using jsnapy" js.snap(config_file, "snapname") # jsnapy closed the connection after the snapshot. # Performing function similar to --snapcheck with --local # runs the tests on stored snapshots named snapname. # jsnapy doesnt open connection # To use this command one has to first create snapshot snapvalue = js.snapcheck(config_file, "snapname", local=True) # printing the result print "comparing snapshots against predefined criteria using jsnapy" for snapcheck in snapvalue: # print "\n -----------snapcheck----------" # print "Tested on", snapcheck.device # print "Final result: ", snapcheck.result # print "Total passed: ", snapcheck.no_passed # print "Total failed:", snapcheck.no_failed pprint(dict(snapcheck.test_details))
### Example showing how to use existing device connection ### from jnpr.jsnapy import SnapAdmin from pprint import pprint from jnpr.junos import Device dev_obj = Device(host='10.209.61.156', user='******', password='******') dev_obj.open() js = SnapAdmin() config_file = "/etc/jsnapy/testfiles/config_check.yml" # can pass device object # it will not create new connection with device snapchk = js.snapcheck(config_file, "snap", dev=dev_obj) for val in snapchk: print "Tested on", val.device print "Final result: ", val.result print "Total passed: ", val.no_passed print "Total failed:", val.no_failed print val.test_details pprint(dict(val.test_details))