def import_file(xapi, module, ip_address, file_, category): xapi.keygen() params = {'type': 'import', 'category': category, 'key': xapi.api_key} filename = os.path.basename(file_) mef = requests_toolbelt.MultipartEncoder(fields={ 'file': (filename, open(file_, 'rb'), 'application/octet-stream') }) r = requests.post('https://' + ip_address + '/api/', verify=module.params['validate_certs'], params=params, headers={'Content-Type': mef.content_type}, data=mef) # if something goes wrong just raise an exception r.raise_for_status() resp = xml.etree.ElementTree.fromstring(r.content) if resp.attrib['status'] == 'error': module.fail_json(msg=r.content) return True, filename
def retrieve_api_key(self, api_username, api_password): """Return an API key for a username and password Given a username and password, return the API key of that user for this PAN Device. The username and password are not stored, and the API key is returned. It is up to the caller to store it in an instance variable if desired. Args: api_username: The username for which to get an API key api_password: The password for the username specified Returns: A string containing the API key Raises: PanDeviceError: If unable to retrieve the API key for reasons other than an API connectivity problem PanXapiError: Raised by pan.xapi module for API errors """ self._logger.info("Getting API Key from %s for user %s", self.hostname, api_username) xapi = pan.xapi.PanXapi(api_username=api_username, api_password=api_password, hostname=self.hostname, port=self.port) xapi.keygen() #TODO: verify this is a good way to error check if xapi.status == 'success': return xapi.api_key else: error_msg = 'Unable to retrieve apikey: %s' % xapi.status raise PanDeviceError(error_msg)
def import_file(xapi, module, ip_address, file_, category): xapi.keygen() params = { 'type': 'import', 'category': category, 'key': xapi.api_key } filename = os.path.basename(file_) mef = requests_toolbelt.MultipartEncoder( fields={ 'file': (filename, open(file_, 'rb'), 'application/octet-stream') } ) r = requests.post( 'https://'+ip_address+'/api/', verify=False, params=params, headers={'Content-Type': mef.content_type}, data=mef ) # if something goes wrong just raise an exception r.raise_for_status() resp = xml.etree.ElementTree.fromstring(r.content) if resp.attrib['status'] == 'error': module.fail_json(msg=r.content) return True, filename
def _retrieve_api_key(self): """Return an API key for a username and password Given a username and password, return the API key of that user for this PAN Device. The username and password are not stored, and the API key is returned. It is up to the caller to store it in an instance variable if desired. Returns: A string containing the API key Raises: PanDeviceError: If unable to retrieve the API key for reasons other than an API connectivity problem PanXapiError: Raised by pan.xapi module for API errors """ self._logger.debug("Getting API Key from %s for user %s" % (self.hostname, self._api_username)) if self._classify_exceptions: xapi = PanDevice.XapiWrapper(pan_device=self, api_username=self._api_username, api_password=self._api_password, hostname=self.hostname, port=self.port, timeout=self.timeout) else: xapi = pan.xapi.PanXapi(api_username=self._api_username, api_password=self._api_password, hostname=self.hostname, port=self.port, timeout=self.timeout) xapi.keygen() return xapi.api_key
def _retrieve_api_key(self): """Return an API key for a username and password Given a username and password, return the API key of that user for this PAN Device. The username and password are not stored, and the API key is returned. It is up to the caller to store it in an instance variable if desired. Returns: A string containing the API key Raises: PanDeviceError: If unable to retrieve the API key for reasons other than an API connectivity problem PanXapiError: Raised by pan.xapi module for API errors """ self._logger.debug("Getting API Key from %s for user %s" % (self.hostname, self._api_username)) if self._classify_exceptions: xapi = PanDevice.XapiWrapper( pan_device=self, api_username=self._api_username, api_password=self._api_password, hostname=self.hostname, port=self.port, timeout=self.timeout ) else: xapi = pan.xapi.PanXapi( api_username=self._api_username, api_password=self._api_password, hostname=self.hostname, port=self.port, timeout=self.timeout ) xapi.keygen() return xapi.api_key
def main(): try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # Windows pass set_encoding() options = parse_opts() if options['debug']: logger = logging.getLogger() if options['debug'] == 3: logger.setLevel(pan.xapi.DEBUG3) elif options['debug'] == 2: logger.setLevel(pan.xapi.DEBUG2) elif options['debug'] == 1: logger.setLevel(pan.xapi.DEBUG1) # log_format = '%(levelname)s %(name)s %(message)s' log_format = '%(message)s' handler = logging.StreamHandler() formatter = logging.Formatter(log_format) handler.setFormatter(formatter) logger.addHandler(handler) if options['cafile'] or options['capath']: ssl_context = create_ssl_context(options['cafile'], options['capath']) else: ssl_context = None try: xapi = pan.xapi.PanXapi(timeout=options['timeout'], tag=options['tag'], use_http=options['use_http'], use_get=options['use_get'], api_username=options['api_username'], api_password=options['api_password'], api_key=options['api_key'], hostname=options['hostname'], port=options['port'], serial=options['serial'], ssl_context=ssl_context) except pan.xapi.PanXapiError as msg: print('pan.xapi.PanXapi:', msg, file=sys.stderr) sys.exit(1) if options['debug'] > 2: print('xapi.__str__()===>\n', xapi, '\n<===', sep='', file=sys.stderr) extra_qs_used = False try: if options['keygen']: action = 'keygen' if options['ad_hoc'] is not None: extra_qs_used = True xapi.keygen(extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if (options['api_username'] and options['api_password'] and options['hostname'] and options['tag']): # .panrc d = datetime.now() print('# %s generated: %s' % (os.path.basename( sys.argv[0]), d.strftime('%Y/%m/%d %H:%M:%S'))) print('hostname%%%s=%s' % (options['tag'], options['hostname'])) print('api_key%%%s=%s' % (options['tag'], xapi.api_key)) else: print('API key: "%s"' % xapi.api_key) if options['show']: action = 'show' if options['ad_hoc'] is not None: extra_qs_used = True xapi.show(xpath=options['xpath'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['get']: action = 'get' if options['ad_hoc'] is not None: extra_qs_used = True xapi.get(xpath=options['xpath'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['delete']: action = 'delete' if options['ad_hoc'] is not None: extra_qs_used = True xapi.delete(xpath=options['xpath'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['edit']: action = 'edit' if options['ad_hoc'] is not None: extra_qs_used = True xapi.edit(xpath=options['xpath'], element=options['element'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['set']: action = 'set' if options['ad_hoc'] is not None: extra_qs_used = True xapi.set(xpath=options['xpath'], element=options['element'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['dynamic-update']: action = 'dynamic-update' kwargs = { 'cmd': options['cmd'], } if options['ad_hoc'] is not None: extra_qs_used = True kwargs['extra_qs'] = options['ad_hoc'] if len(options['vsys']): kwargs['vsys'] = options['vsys'][0] xapi.user_id(**kwargs) print_status(xapi, action) print_response(xapi, options) if options['move'] is not None: action = 'move' if options['ad_hoc'] is not None: extra_qs_used = True xapi.move(xpath=options['xpath'], where=options['move'], dst=options['dst'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['rename']: action = 'rename' if options['ad_hoc'] is not None: extra_qs_used = True xapi.rename(xpath=options['xpath'], newname=options['dst'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['clone']: action = 'clone' if options['ad_hoc'] is not None: extra_qs_used = True xapi.clone(xpath=options['xpath'], xpath_from=options['src'], newname=options['dst'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['override']: action = 'override' if options['ad_hoc'] is not None: extra_qs_used = True xapi.override(xpath=options['xpath'], element=options['element'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['export'] is not None: action = 'export' if options['ad_hoc'] is not None: extra_qs_used = True if options['pcapid'] is not None: xapi.export(category=options['export'], pcapid=options['pcapid'], search_time=options['stime'], serialno=options['serial'], extra_qs=options['ad_hoc']) else: xapi.export(category=options['export'], from_name=options['src'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['pcap_listing']: pcap_listing(xapi, options['export']) save_attachment(xapi, options) if options['log'] is not None: action = 'log' if options['ad_hoc'] is not None: extra_qs_used = True xapi.log(log_type=options['log'], nlogs=options['nlogs'], skip=options['skip'], filter=options['filter'], interval=options['interval'], timeout=options['job_timeout'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['op'] is not None: action = 'op' kwargs = { 'cmd': options['op'], 'cmd_xml': options['cmd_xml'], } if options['ad_hoc'] is not None: extra_qs_used = True kwargs['extra_qs'] = options['ad_hoc'] if len(options['vsys']): kwargs['vsys'] = options['vsys'][0] xapi.op(**kwargs) print_status(xapi, action) print_response(xapi, options) if (options['commit'] or options['commit_all']): if options['cmd']: cmd = options['cmd'] if options['cmd_xml']: cmd = xapi.cmd_xml(cmd) else: c = pan.commit.PanCommit(validate=options['validate'], force=options['force'], commit_all=options['commit_all'], merge_with_candidate=options['merge']) for part in options['partial']: if part == 'device-and-network-excluded': c.device_and_network_excluded() elif part == 'policy-and-objects-excluded': c.policy_and_objects_excluded() elif part == 'shared-object-excluded': c.shared_object_excluded() elif part == 'no-vsys': c.no_vsys() elif part == 'vsys': c.vsys(options['vsys']) if options['serial'] is not None: c.device(options['serial']) if options['group'] is not None: c.device_group(options['group']) if options['commit_all'] and options['vsys']: c.vsys(options['vsys'][0]) cmd = c.cmd() kwargs = { 'cmd': cmd, 'sync': options['sync'], 'interval': options['interval'], 'timeout': options['job_timeout'], } if options['ad_hoc'] is not None: extra_qs_used = True kwargs['extra_qs'] = options['ad_hoc'] if options['commit_all']: kwargs['action'] = 'all' action = 'commit' xapi.commit(**kwargs) print_status(xapi, action) print_response(xapi, options) if not extra_qs_used and options['ad_hoc'] is not None: action = 'ad_hoc' xapi.ad_hoc(qs=options['ad_hoc'], xpath=options['xpath'], modify_qs=options['modify']) print_status(xapi, action) print_response(xapi, options) except pan.xapi.PanXapiError as msg: print_status(xapi, action, str(msg)) print_response(xapi, options) sys.exit(1) sys.exit(0)
def main(): try: signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # Windows pass set_encoding() options = parse_opts() if options['debug']: logger = logging.getLogger() if options['debug'] == 3: logger.setLevel(pan.xapi.DEBUG3) elif options['debug'] == 2: logger.setLevel(pan.xapi.DEBUG2) elif options['debug'] == 1: logger.setLevel(pan.xapi.DEBUG1) # log_format = '%(levelname)s %(name)s %(message)s' log_format = '%(message)s' handler = logging.StreamHandler() formatter = logging.Formatter(log_format) handler.setFormatter(formatter) logger.addHandler(handler) if options['cafile'] or options['capath']: ssl_context = create_ssl_context(options['cafile'], options['capath']) else: ssl_context = None try: xapi = pan.xapi.PanXapi(timeout=options['timeout'], tag=options['tag'], use_http=options['use_http'], use_get=options['use_get'], api_username=options['api_username'], api_password=options['api_password'], api_key=options['api_key'], hostname=options['hostname'], port=options['port'], serial=options['serial'], ssl_context=ssl_context) except pan.xapi.PanXapiError as msg: print('pan.xapi.PanXapi:', msg, file=sys.stderr) sys.exit(1) if options['debug'] > 2: print('xapi.__str__()===>\n', xapi, '\n<===', sep='', file=sys.stderr) extra_qs_used = False try: if options['keygen']: action = 'keygen' if options['ad_hoc'] is not None: extra_qs_used = True xapi.keygen(extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) print('API key: "%s"' % xapi.api_key) if options['show']: action = 'show' if options['ad_hoc'] is not None: extra_qs_used = True xapi.show(xpath=options['xpath'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['get']: action = 'get' if options['ad_hoc'] is not None: extra_qs_used = True xapi.get(xpath=options['xpath'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['delete']: action = 'delete' if options['ad_hoc'] is not None: extra_qs_used = True xapi.delete(xpath=options['xpath'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['edit']: action = 'edit' if options['ad_hoc'] is not None: extra_qs_used = True xapi.edit(xpath=options['xpath'], element=options['element'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['set']: action = 'set' if options['ad_hoc'] is not None: extra_qs_used = True xapi.set(xpath=options['xpath'], element=options['element'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['dynamic-update']: action = 'dynamic-update' kwargs = { 'cmd': options['cmd'], } if options['ad_hoc'] is not None: extra_qs_used = True kwargs['extra_qs'] = options['ad_hoc'] if len(options['vsys']): kwargs['vsys'] = options['vsys'][0] xapi.user_id(**kwargs) print_status(xapi, action) print_response(xapi, options) if options['move'] is not None: action = 'move' if options['ad_hoc'] is not None: extra_qs_used = True xapi.move(xpath=options['xpath'], where=options['move'], dst=options['dst'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['rename']: action = 'rename' if options['ad_hoc'] is not None: extra_qs_used = True xapi.rename(xpath=options['xpath'], newname=options['dst'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['clone']: action = 'clone' if options['ad_hoc'] is not None: extra_qs_used = True xapi.clone(xpath=options['xpath'], xpath_from=options['src'], newname=options['dst'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['override']: action = 'override' if options['ad_hoc'] is not None: extra_qs_used = True xapi.override(xpath=options['xpath'], element=options['element'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['export'] is not None: action = 'export' if options['ad_hoc'] is not None: extra_qs_used = True if options['pcapid'] is not None: xapi.export(category=options['export'], pcapid=options['pcapid'], search_time=options['stime'], serialno=options['serial'], extra_qs=options['ad_hoc']) else: xapi.export(category=options['export'], from_name=options['src'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['pcap_listing']: pcap_listing(xapi, options['export']) save_attachment(xapi, options) if options['log'] is not None: action = 'log' if options['ad_hoc'] is not None: extra_qs_used = True xapi.log(log_type=options['log'], nlogs=options['nlogs'], skip=options['skip'], filter=options['filter'], interval=options['interval'], timeout=options['job_timeout'], extra_qs=options['ad_hoc']) print_status(xapi, action) print_response(xapi, options) if options['op'] is not None: action = 'op' kwargs = { 'cmd': options['op'], 'cmd_xml': options['cmd_xml'], } if options['ad_hoc'] is not None: extra_qs_used = True kwargs['extra_qs'] = options['ad_hoc'] if len(options['vsys']): kwargs['vsys'] = options['vsys'][0] xapi.op(**kwargs) print_status(xapi, action) print_response(xapi, options) if (options['commit'] or options['commit_all']): if options['cmd']: cmd = options['cmd'] if options['cmd_xml']: cmd = xapi.cmd_xml(cmd) else: c = pan.commit.PanCommit(validate=options['validate'], force=options['force'], commit_all=options['commit_all'], merge_with_candidate= options['merge']) for part in options['partial']: if part == 'device-and-network-excluded': c.device_and_network_excluded() elif part == 'policy-and-objects-excluded': c.policy_and_objects_excluded() elif part == 'shared-object-excluded': c.shared_object_excluded() elif part == 'no-vsys': c.no_vsys() elif part == 'vsys': c.vsys(options['vsys']) if options['serial'] is not None: c.device(options['serial']) if options['group'] is not None: c.device_group(options['group']) if options['commit_all'] and options['vsys']: c.vsys(options['vsys'][0]) cmd = c.cmd() kwargs = { 'cmd': cmd, 'sync': options['sync'], 'interval': options['interval'], 'timeout': options['job_timeout'], } if options['ad_hoc'] is not None: extra_qs_used = True kwargs['extra_qs'] = options['ad_hoc'] if options['commit_all']: kwargs['action'] = 'all' action = 'commit' xapi.commit(**kwargs) print_status(xapi, action) print_response(xapi, options) if not extra_qs_used and options['ad_hoc'] is not None: action = 'ad_hoc' xapi.ad_hoc(qs=options['ad_hoc'], xpath=options['xpath'], modify_qs=options['modify']) print_status(xapi, action) print_response(xapi, options) except pan.xapi.PanXapiError as msg: print_status(xapi, action, msg) print_response(xapi, options) sys.exit(1) sys.exit(0)
def main(): set_encoding() options = parse_opts() try: xapi = pan.xapi.PanXapi(debug=options['debug'], timeout=options['timeout'], tag=options['tag'], use_http=options['use_http'], use_get=options['use_get'], api_username=options['api_username'], api_password=options['api_password'], api_key=options['api_key'], hostname=options['hostname'], port=options['port'], serial=options['serial'], cafile=options['cafile'], capath=options['capath']) except pan.xapi.PanXapiError as msg: print('pan.xapi.PanXapi:', msg, file=sys.stderr) sys.exit(1) if options['debug'] > 2: print('xapi.__str__()===>\n', xapi, '\n<===', sep='', file=sys.stderr) try: if options['ad_hoc'] is not None: action = 'ad_hoc' xapi.ad_hoc(qs=options['ad_hoc'], xpath=options['xpath'], modify_qs=options['modify']) print_status(xapi, action) print_response(xapi, options) if options['keygen']: action = 'keygen' xapi.keygen() print_status(xapi, action) print_response(xapi, options) print('API key: "%s"' % xapi.api_key) if options['show']: action = 'show' xapi.show(xpath=options['xpath']) print_status(xapi, action) print_response(xapi, options) if options['get']: action = 'get' xapi.get(xpath=options['xpath']) print_status(xapi, action) print_response(xapi, options) if options['delete']: action = 'delete' xapi.delete(xpath=options['xpath']) print_status(xapi, action) print_response(xapi, options) if options['edit']: action = 'edit' xapi.edit(xpath=options['xpath'], element=options['element']) print_status(xapi, action) print_response(xapi, options) if options['set']: action = 'set' xapi.set(xpath=options['xpath'], element=options['element']) print_status(xapi, action) print_response(xapi, options) if options['dynamic-update']: action = 'dynamic-update' kwargs = { 'cmd': options['cmd'], } if len(options['vsys']): kwargs['vsys'] = options['vsys'][0] xapi.user_id(**kwargs) print_status(xapi, action) print_response(xapi, options) if options['move'] is not None: action = 'move' xapi.move(xpath=options['xpath'], where=options['move'], dst=options['dst']) print_status(xapi, action) print_response(xapi, options) if options['rename']: action = 'rename' xapi.rename(xpath=options['xpath'], newname=options['dst']) print_status(xapi, action) print_response(xapi, options) if options['clone']: action = 'clone' xapi.clone(xpath=options['xpath'], xpath_from=options['src'], newname=options['dst']) print_status(xapi, action) print_response(xapi, options) if options['override']: action = 'override' xapi.override(xpath=options['xpath'], element=options['element']) print_status(xapi, action) print_response(xapi, options) if options['export'] is not None: action = 'export' xapi.export(category=options['export'], from_name=options['src']) print_status(xapi, action) print_response(xapi, options) if options['pcap_listing']: pcap_listing(xapi, options) save_pcap(xapi, options) if options['log'] is not None: action = 'log' xapi.log(log_type=options['log'], nlogs=options['nlogs'], skip=options['skip'], filter=options['filter'], interval=options['interval'], timeout=options['job_timeout']) print_status(xapi, action) print_response(xapi, options) if options['op'] is not None: action = 'op' kwargs = { 'cmd': options['op'], 'cmd_xml': options['cmd_xml'], } if len(options['vsys']): kwargs['vsys'] = options['vsys'][0] xapi.op(**kwargs) print_status(xapi, action) print_response(xapi, options) if (options['commit'] or options['commit_all']): if options['cmd']: cmd = options['cmd'] if options['cmd_xml']: cmd = xapi.cmd_xml(cmd) else: c = pan.commit.PanCommit(debug=options['debug'], validate=options['validate'], force=options['force'], commit_all=options['commit_all'], merge_with_candidate= options['merge']) for part in options['partial']: if part == 'device-and-network-excluded': c.device_and_network_excluded() elif part == 'policy-and-objects-excluded': c.policy_and_objects_excluded() elif part == 'shared-object-excluded': c.shared_object_excluded() elif part == 'no-vsys': c.no_vsys() elif part == 'vsys': c.vsys(options['vsys']) if options['serial'] is not None: c.device(options['serial']) if options['group'] is not None: c.device_group(options['group']) if options['commit_all'] and options['vsys']: c.vsys(options['vsys'][0]) cmd = c.cmd() kwargs = { 'cmd': cmd, 'sync': options['sync'], 'interval': options['interval'], 'timeout': options['job_timeout'], } if options['commit_all']: kwargs['action'] = 'all' action = 'commit' xapi.commit(**kwargs) print_status(xapi, action) print_response(xapi, options) except pan.xapi.PanXapiError as msg: print_status(xapi, action, msg) print_response(xapi, options) sys.exit(1) sys.exit(0)