def main(): signal.signal(signal.SIGINT, keyboardInterruptHandler) try: pano = panorama.Panorama(ip, user, pw) dg = panorama.DeviceGroup(DEVICE_GROUP) pano.add(dg) postrulebase = policies.PostRulebase() dg.add(postrulebase) rule_refresh = policies.SecurityRule.refreshall(postrulebase) rule_list = postrulebase.children for rule in rule_list: if SPLIT_DISABLED or (not SPLIT_DISABLED and not rule.disabled): if len(rule.fromzone) > 1 and len(rule.tozone) > 1: if rule.tag == None or not RULE_TAG in rule.tag: rule_clone(rule, pano, postrulebase) print('') print('Total source rules cloned: ' + str(i)) except Exception as e: print(e) print('Error. Verify credentials/device address/device group name and try again.') exit(0)
def main(): args = get_cli_arguments() setup_logging(args) # The Panorama object. This is the root object of the config tree. pano = panorama.Panorama(hostname=HOSTNAME, api_key=APIKEY, ) # Add the devicegroup as a child of the Panorama if args.devicegroup is not None: scope = pano.add(panorama.DeviceGroup(args.devicegroup)) else: scope = pano # Create a dynamic address group in the required scope addressgroup = scope.add(objects.AddressGroup(name=args.name, dynamic_value=args.match, description=args.description, tag=args.tag, )) # Push the new dynamic address group to the live Panorama device addressgroup.create() # Perform a commit if requested if args.commit or args.commitall: pano.commit(sync=True) if args.commitall: pano.commit_all(sync=True, sync_all=True, devicegroup=args.devicegroup)
def setUp(self): logging.basicConfig(level=10) # Get current test (in string with format): # tests.test_pandevice.TestPandevice.test_refresh_interfaces_mock test_method = self.id() if test_method.endswith("_mock"): # This is a test with a mock firewall mock.patch.object(firewall.pan.xapi, 'PanXapi', mock.MagicMock()) self.d = firewall.Firewall(hostname="fake-hostname", api_username="******", api_password="******", ) self.d._retrieve_api_key = mock.Mock(return_value="fakekey") # Trigger attempt to populate API key by accessing xapi self.xapi = self.d.xapi else: # This is a test against a real firewall and panorama self.p = panorama.Panorama(hostname=TESTRAMA_HOSTNAME, api_username=TESTRAMA_USERNAME, api_password=TESTRAMA_PASSWORD, ) self.d = firewall.Firewall(hostname=TESTFW_HOSTNAME, api_username=TESTFW_USERNAME, api_password=TESTFW_PASSWORD, )
def panoramaCommitAll(pn, devicegroup): pano = panorama.Panorama(pn['hostname'], pn['username'], pn['password']) print("Committing on Panorama") pano.commit(sync=True) print("Committed on Panorama") print("Committing All on Panorama") pano.commit_all(sync=True, sync_all=True, devicegroup=devicegroup) print("Committed All on Panorama")
def pano_connect(): # Instantiate a Firewall with serial fw = firewall.Firewall(serial=fw_serial) # Instantiate a Panorama with hostname and credentials pano = panorama.Panorama(pano_addr, pano_user, pano_pass) # Add the Firewall as a child of Panorama pano.add(fw) return fw, pano
def test_device_group_xpath_unchanged(): expected = "/config/devices/entry[@name='localhost.localdomain']/device-group/entry[@name='somegroup']/address/entry[@name='intnet']" pano = panorama.Panorama('127.0.0.1') dg = panorama.DeviceGroup('somegroup') ao = objects.AddressObject('intnet', '192.168.0.0/16') pano.add(dg) dg.add(ao) assert expected == ao.xpath()
def panoramaCommitAll(pn, devicegroup, module): try: pano = panorama.Panorama(pn['hostname'], pn['username'], pn['password']) #print("Committing on Panorama") pano.commit(sync=True) #print("Committed on Panorama") #print("Committing All on Panorama") pano.commit_all(sync=True, sync_all=True, devicegroup=devicegroup) #print("Committed All on Panorama") except Exception as e: module.fail_json(msg='Fail on commit: {}'.format(e)) return True
def fix_nat(self, host, user, pw): pano = panorama.Panorama(host, user, pw) panorama.DeviceGroup.refreshall(pano, add=True) for dg in pano.children: prerulebase = policies.PreRulebase() dg.add(prerulebase) natrules = policies.NatRule.refreshall(prerulebase) self.fix_nat_rules(dg, natrules) securityrules = policies.SecurityRule.refreshall(prerulebase) self.fix_security_rules(dg, securityrules)
def get_active_pano(): """ Read Panorama IPs from file, for each IP make Panorama connection, get HA status, and then return the active device Returns ------- pano : Panorama A PanDevice for Panorama """ key = config.paloalto['key'] panorama_ips = config.paloalto['panorama_ips'] if len(panorama_ips) == 1: pano = panorama.Panorama(hostname=panorama_ips[0], api_key=key) return pano else: for ip in panorama_ips: pano = panorama.Panorama(hostname=ip, api_key=key) ha_status = get_ha_status(pano) if ha_status == 'active': return pano
def get_pano_connection(): """ Make Panorama connection Returns ------- pano : Panorama A PanDevice for Panorama """ key = config.paloalto['key'] panorama_ip = config.paloalto['panorama_ip'] pano = panorama.Panorama(hostname=panorama_ip, api_key=key) return pano
def main(): args = get_cli_arguments() setup_logging(args) # The Panorama object. This is the root object of the config tree. pano = panorama.Panorama( hostname=HOSTNAME, api_key=APIKEY, ) # Perform a commit if requested pano.commit(sync=True) if args.commitall: pano.commit_all(sync=True, sync_all=True, devicegroup=args.devicegroup)
def __init__(self, *args, **kwargs): """ We need additional information for this driver """ # create a panorama object self.pano = panorama.Panorama(kwargs['ip'], kwargs['username'], kwargs['password']) self.dev_group = None self.dev_group_post_rulebase = None self.dev_group_pre_rulebase = None self.pano_post_rulebase = None self.pano_pre_rulebase = None # now call the super super(PaloAltoPanoramaDriver, self).__init__(*args, **kwargs)
def main(): args = get_cli_arguments() setup_logging(args) # The Panorama object. This is the root object of the config tree. pano = panorama.Panorama( hostname=HOSTNAME, api_key=APIKEY, ) # Add the devicegroup as a child of the Panorama if args.devicegroup is not None: scope = pano.add(panorama.DeviceGroup(args.devicegroup)) else: scope = pano # Create a security rule in the required scope rulebase = scope.add(policies.PreRulebase()) rule = rulebase.add( policies.SecurityRule( args.name, args.szone, args.dzone, source=args.saddr, destination=args.daddr, application=args.application, action=args.action, log_setting=args.log, group=args.group, virus=args.virus, spyware=args.spyware, vulnerability=args.threat, url_filtering=args.url, file_blocking=args.file, wildfire_analysis=args.wildfire, data_filtering=args.data, tag=args.tag, description=args.description, )) # Push the new security rule to the live Panorama device rule.create() if args.above is not None: pano.xapi.move(rule.xpath(), "before", args.above)
def _check(obj, vsys, with_pano, chk_import=False): if chk_import: func = 'xpath_import_base' else: func = 'xpath' fw = firewall.Firewall('127.0.0.1', 'admin', 'admin', serial='01234567890') fw.vsys = vsys fw.add(obj) if with_pano: pano = panorama.Panorama('127.0.0.1', 'admin2', 'admin2') pano.add(fw) expected = getattr(obj, func)() fw.remove(obj) fw.vsys = None vsys = device.Vsys(vsys or 'vsys1') fw.add(vsys) vsys.add(obj) result = getattr(obj, func)() assert expected == result
import time import datetime from pandevice import panorama from pandevice import policies def display_process_id(process_name): output_bytes = pano.op('show system software status', xml=True) output_str = output_bytes.decode('utf-8') output_lines = output_str.split('\n') for line in output_lines: if process_name in line: return line pano = panorama.Panorama('10.46.164.193', 'zmacharia', 'paloalto') dallas_dg = panorama.DeviceGroup('Test') # creating device group object pano.add(dallas_dg) # adding device group to the panorama object rulebase = policies.PreRulebase() dallas_dg.add(rulebase) rules = policies.SecurityRule.refreshall(rulebase, add=False) print(f'Before loop: {display_process_id("configd")}') print(f'Starting timestamp: {datetime.datetime.now()}') t1_start = time.process_time() for rule in rules: if rule.log_setting is None: rulebase.add(policies.SecurityRule(rule.name,
# - Delete objects # # Author: Philippe Glohr # Date: 2018-10 # Version: 0.01 @ 20181029 import argparse import pandevice from pandevice import panorama from pandevice import objects from IPython import embed # Fixed variables PAN_IP_address = "panorama_hostname" PAN_API_KEY = "API-key" pano = panorama.Panorama(PAN_IP_address, api_key=PAN_API_KEY) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cmd', type=str, help='Operation (Add, Mod or Del)', required=True) parser.add_argument('--name', type=str, help='Object name', required=True) parser.add_argument('--ip', type=str, default='', help='Object IP address') parser.add_argument('--type', type=str, default='fqdn', help='Object type fqdn or ip-netmask') parser.add_argument('--desc', help="Object description") parser.add_argument('--tag', help="List of tags separated with ,")
def commit_panorma(): "Commit configuration on Panorma to the FW's" _panorama = panorama.Panorama('10.8.202.117', 'admin', 'admin') _panorama.commit_all(sync=True, sync_all=True, exception=True, devicegroup='cap_one_dg')
def init(): ''' Environment variables: PD_USERNAME PD_PASSWORD PD_PANORAMAS PD_FIREWALLS ''' global live_devices global one_fw_per_version global one_device_per_version global one_panorama_per_version global ha_pairs global panorama_fw_combinations # Get os.environ stuff to set the live_devices global. try: username = os.environ['PD_USERNAME'] password = os.environ['PD_PASSWORD'] panos = os.environ['PD_PANORAMAS'].split() fws = os.environ['PD_FIREWALLS'].split() except KeyError as e: print('NOT RUNNING LIVE TESTS - missing "{0}"'.format(e)) return # Add each panorama to the live_devices. for hostname in panos: c = panorama.Panorama(hostname, username, password) try: c.refresh_system_info() except Exception as e: raise ValueError('Failed to connect to panorama {0}: {1}'.format( hostname, e)) # There should only be one panorama per version. version = c._version_info if version in live_devices: raise ValueError('Two panoramas, same version: {0} and {1}'.format( live_devices[version]['pano'].hostname, hostname)) live_devices.setdefault(version, {'fws': [], 'pano': None}) live_devices[version]['pano'] = c # Add each firewall to the live_devices. for hostname in fws: c = firewall.Firewall(hostname, username, password) try: c.refresh_system_info() except Exception as e: raise ValueError('Failed to connect to firewall {0}: {1}'.format( hostname, e)) # Multiple firewalls are allowed per version, but only ever the first # two will be used. version = c._version_info live_devices.setdefault(version, {'fws': [], 'pano': None}) live_devices[version]['fws'].append(c) # Set: # one_fw_per_version # one_device_type_per_version # one_panorama_per_version for version in live_devices: pano = live_devices[version]['pano'] fws = live_devices[version]['fws'] if fws: fw = random.choice(fws) one_device_type_per_version.append((fw, desc(fw=version))) one_fw_per_version.append((fw, desc(fw=version))) if pano is not None: one_panorama_per_version.append((pano, desc(pano=version))) one_device_type_per_version.append((pano, desc(pano=version))) # Set: ha_pairs for version in live_devices: fws = live_devices[version]['fws'] if len(fws) >= 2: ha_pairs.append((fws[:2], version)) # Set panorama_fw_combinations for pano_version in live_devices: pano = live_devices[pano_version]['pano'] if pano is None: continue for fw_version in live_devices: fws = live_devices[fw_version]['fws'] if not fws or pano_version < fw_version: continue fw = random.choice(fws) panorama_fw_combinations.append(( (pano, fw), desc(pano_version, fw_version), ))
def get_pano_info(collection): """ Gets Palo Panorama info and adds/updates database Parameters ---------- collection : Collection A MongoDB database collection """ logger.info('Starting') key = config.paloalto['key'] panorama_ips = config.paloalto['panorama_ips'] for ip in panorama_ips: logger.debug(ip) pano = panorama.Panorama(hostname=ip, api_key=key) results = pano.op('show system info') serial = results.find('./result/system/serial').text hostname = results.find('./result/system/hostname').text ip_addr = results.find('./result/system/ip-address').text family = results.find('./result/system/family').text model = results.find('./result/system/model').text sw_version = results.find('./result/system/sw-version').text find_results = collection.find_one({"ip-address": ip_addr}, { 'serial': 1, 'sw-version': 1, '_id': 0 }) logger.debug(find_results) if find_results is None: insert_results = collection.insert({ 'serial': serial, 'hostname': hostname, 'ip-address': ip_addr, 'family': family, 'model': model, 'sw-version': sw_version }) logger.debug(insert_results) else: stored_serial = find_results.get('serial') if stored_serial != serial: update_serial = collection.update_one( {"ip-address": ip_addr}, {'$set': { 'serial': serial }}) logger.debug( 'Update Serial Number -- Matched: {} -- Modified: {}'. format(update_serial.matched_count, update_serial.modified_count)) stored_sw_version = find_results.get('sw-version') if stored_sw_version != sw_version: update_sw_version = collection.update_one( {"ip-address": ip_addr}, {'$set': { 'sw-version': sw_version }}) logger.debug( 'Update Software Version -- Matched: {} -- Modified: {}'. format(update_sw_version.matched_count, update_sw_version.modified_count))
def __init__(self, host, key, pano=False): if pano == True: self.conn = panorama.Panorama(hostname=host, api_key=key) else: self.conn = firewall.Firewall(hostname=host, api_key=key)