Esempio n. 1
0
def validate_snippet_present(service, context):
    """
    Checks all xpaths in the service to validate if they are already present in panorama
    Status codes documented here:
        https://www.paloaltonetworks.com/documentation/71/pan-os/xml-api/pan-os-xml-api-error-codes
    :param service: dict of service params generared by snippet_utils.load_snippet_with_name()
    :param context: dict containing all jinja variables as key / value pairs
    :return: boolean True if found, false if any xpath is not found
    """
    xapi = panorama_login()

    if xapi is None:
        print('Could not login to Panorama')
        return False

    try:
        for snippet in service['snippets']:
            xpath = snippet['xpath']
            xpath_template = Environment(
                loader=BaseLoader()).from_string(xpath)
            xpath_string = xpath_template.render(context)
            xapi.get(xpath=xpath_string)
            if xapi.status_code == '19' or xapi.status_code == '20':
                print('xpath is already present')
            elif xapi.status_code == '7':
                print('xpath was NOT found')
                return False

        # all xpaths were found
        return True

    except pan.xapi.PanXapiError as pxe:
        print('Could not validate snippet was present!')
        print(pxe)
        return False
Esempio n. 2
0
def get_device_groups_from_panorama():
    xapi = panorama_login()
    device_group_xpath = "/config/devices/entry[@name='localhost.localdomain']/device-group"

    services = list()

    if xapi is None:
        print('Could not login to Panorama')
        return services

    try:
        xapi.get(device_group_xpath)
        xml = xapi.xml_result()
    except pan.xapi.PanXapiError as pxe:
        print('Could not get device groups from Panorama')
        print(pxe)
        return services

    if xml is None:
        print('No services currently defined in panorama')
        return services

    doc = et.fromstring(xml)
    for dg in doc:
        if 'name' in dg.attrib:
            service = dict()
            for tag in dg.findall('./tag/entry'):
                if 'name' in tag.attrib and ':' in tag.attrib['name']:
                    k, v = tag.attrib['name'].split(':')
                    service[k] = v
                    service['name'] = dg.attrib['name']

            services.append(service)

    return services
Esempio n. 3
0
def get_device_groups_from_panorama() -> list:
    """
    Return a list of device groups from panorama instance
    :return: List of dicts containing device group entries
    """
    xapi = panos_login()
    device_group_xpath = "/config/devices/entry[@name='localhost.localdomain']/device-group"

    services = list()

    try:
        xapi.get(device_group_xpath)
        xml = xapi.xml_result()
    except pan.xapi.PanXapiError as pxe:
        print('Could not get device groups from Panorama')
        print(pxe)
        return services

    doc = elementTree.fromstring(xml)
    for dg in doc:
        if 'name' in dg.attrib:
            service = dict()
            for tag in dg.findall('./tag/entry'):
                if 'name' in tag.attrib and ':' in tag.attrib['name']:
                    k, v = tag.attrib['name'].split(':')
                    service[k] = v
                    service['name'] = dg.attrib['name']

            services.append(service)

    return services
Esempio n. 4
0
def set_dns_server(xapi, new_dns_server, primary=True):
    if primary:
        tag = "primary"
    else:
        tag = "secondary"
    xpath = _XPATH_DNS_SERVERS + "/" + tag

    # check the current element value
    xapi.get(xpath)
    val = xapi.element_root.find(".//" + tag)
    if val is not None:
        # element exists
        val = val.text
    if val == new_dns_server:
        return False

    element = "<%(tag)s>%(value)s</%(tag)s>" %\
              dict(tag=tag, value=new_dns_server)
    xapi.edit(xpath, element)

    return True
def set_dns_server(xapi, new_dns_server, primary=True):
    if primary:
        tag = "primary"
    else:
        tag = "secondary"
    xpath = _XPATH_DNS_SERVERS + "/" + tag

    # check the current element value
    xapi.get(xpath)
    val = xapi.element_root.find(".//" + tag)
    if val is not None:
        # element exists
        val = val.text
    if val == new_dns_server:
        return False

    element = "<%(tag)s>%(value)s</%(tag)s>" %\
              dict(tag=tag, value=new_dns_server)
    xapi.edit(xpath, element)

    return True
Esempio n. 6
0
def addressgroup_exists(xapi, group_name):
    xapi.get(_ADDRGROUP_XPATH % group_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 7
0
def vulnerability_profile_exists(xapi, vulnprofile_name):
    xapi.get(_SERVICE_XPATH % vulnprofile_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 8
0
def address_exists(xapi, address_name):
    xapi.get(_ADDRESS_XPATH % address_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
def mgtprf_exists(xapi, mgtprf_name):
    xpath = _MGT_PRF_XPATH % mgtprf_name
    xapi.get(xpath=xpath)
    router = xapi.element_root.find('.//entry')
    return (router is not None)
def get_publickey(xapi, user):
    xapi.get(xpath=_PKEY_XPATH % user)
    pkey = xapi.element_root.find('.//public-key')
    if pkey is None:
        return None
    return base64.b64decode(pkey.text)
Esempio n. 11
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)
Esempio n. 12
0
def admin_exists(xapi, admin_username):
    xapi.get(_ADMIN_XPATH % admin_username)
    e = xapi.element_root.find('.//entry')
    return e
Esempio n. 13
0
def security_rule_exists(xapi, rule_name):
    xapi.get(_SRULE_XPATH % rule_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
def vulnerability_profile_exists(xapi, vulnprofile_name):
    xapi.get(_SERVICE_XPATH % vulnprofile_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 15
0
def if_exists(xapi, tunnel_unit):
    xpath = _TIF_XPATH % tunnel_unit
    xapi.get(xpath=xpath)
    network = xapi.element_root.find('.//entry')
    return (network is not None)
Esempio n. 16
0
def addressgroup_exists(xapi, group_name):
    xapi.get(_ADDRGROUP_XPATH % group_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 17
0
def if_exists(xapi, if_name):
    xpath = _IF_XPATH % if_name
    xapi.get(xpath=xpath)
    network = xapi.element_root.find('.//layer3')
    return (network is not None)
def if_exists(xapi, tunnel_unit):
    xpath = _TIF_XPATH % tunnel_unit
    xapi.get(xpath=xpath)
    network = xapi.element_root.find('.//entry')
    return (network is not None)
Esempio n. 19
0
def custom_app_exists(xapi, app_name):
    xapi.get(_CUSTOM_APP_XPATH % app_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 20
0
def pg_exists(xapi, pg_name):
    xapi.get(_PG_XPATH % pg_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
def service_exists(xapi, service_name):
    xapi.get(_SERVICE_XPATH % service_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
def admin_exists(xapi, admin_username):
    xapi.get(_ADMIN_XPATH % admin_username)
    e = xapi.element_root.find('.//entry')
    return e
Esempio n. 23
0
def vr_exists(xapi, vr_name):
    xpath = _VR_XPATH % vr_name
    xapi.get(xpath=xpath)
    router = xapi.element_root.find('.//entry')
    return (router is not None)
Esempio n. 24
0
def pg_exists(xapi, pg_name):
    xapi.get(_PG_XPATH % pg_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 25
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 vmmonitor_exists(xapi, monitor_name):
    xapi.get(_VMMONITOR_XPATH % monitor_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
Esempio n. 27
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)
            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)
Esempio n. 28
0
def if_exists(xapi, if_name):
    xpath = _IF_XPATH % if_name
    xapi.get(xpath=xpath)
    network = xapi.element_root.find('.//layer3')
    return (network is not None)
def get_publickey(xapi, user):
    xapi.get(xpath=_PKEY_XPATH % user)
    pkey = xapi.element_root.find('.//public-key')
    if pkey is None:
        return None
    return base64.b64decode(pkey.text)
Esempio n. 30
0
def get_gpp_gateway(xapi, module, portal_name, config_name,
                    type_, gateway_address):
    xapi.get(_GW_PATH % (portal_name, config_name, type_, gateway_address))
    e = xapi.element_root.find('.//entry')
    return e
Esempio n. 31
0
def nat_rule_exists(xapi, rule_name):
    xapi.get(_NAT_XPATH % rule_name)
    e = xapi.element_root.find('.//entry')
    if e is None:
        return False
    return True
def get_gpp_gateway(xapi, module, portal_name, config_name,
                    type_, gateway_address):
    xapi.get(_GW_PATH % (portal_name, config_name, type_, gateway_address))
    e = xapi.element_root.find('.//entry')
    return e