Exemplo n.º 1
0
def main() -> None:
    fw = Firewall("10.0.1.25", "admin", "Pal0Alt0!")
    for index in range(1, 5):
        addobj = fw.add(AddressObject(f"My-new-object-{index}", "1.1.1.1"))
        addobj.create()
    result = fw.op("show system info")
    print(ET.tostring(result))
Exemplo n.º 2
0
def firewall_import(import_fw, import_dict, import_username, import_password,
                    commit):
    pushing_fw = Firewall(import_fw, import_username, import_password)
    AddressObject.refreshall(
        pushing_fw)  #pulls down the address objects in the firewall
    AddressGroup.refreshall(
        pushing_fw, add=True)  # pulls down the address groups in the firewall
    for i in import_dict['addresses']:
        addr = AddressObject(name=i['name'],
                             value=i['value'],
                             description=i['description'],
                             type=i['type'],
                             tag=i['tag'])
        pushing_fw.add(addr)
    start = datetime.datetime.now()
    addr.create_similar()

    for i in import_dict['groups']:
        group = AddressGroup(i['name'], i['static_value'], i['dynamic_value'],
                             i['tag'])
        pushing_fw.add(group)
    start = datetime.datetime.now()
    group.create_similar()
    print(
        f"Imported { len(import_dict['addresses']) } addresses and {len(import_dict['groups'])} groups to { import_fw }"
    )
    print(f"which took: {datetime.datetime.now() - start}")

    if commit is True:
        print(f"As requested, commiting to firewall {import_fw}")
        pushing_fw.commit()

    return import_dict
Exemplo n.º 3
0
def _fw(*args):
    fw = Firewall("127.0.0.1", "admin", "admin", "secret")
    fw._version_info = (9999, 0, 0)

    if len(args) == 0:
        fw.xapi.get = mock.Mock(return_value=object_not_found())
    else:
        prefix = "<response><result>"
        suffix = "</result></response>"
        inner = "".join(x.element_str().decode("utf-8") for x in args)
        fw.xapi.get = mock.Mock(
            return_value=ET.fromstring(prefix + inner + suffix, ))

    return fw
Exemplo n.º 4
0
def main():
    # Create a connection to a firewall and a rulebase to work inside
    fw = Firewall(HOSTNAME, USERNAME, PASSWORD)
    rulebase = fw.add(Rulebase())

    # Fetch all the security rules from the firewall into a list
    rules = SecurityRule.refreshall(rulebase, add=False)

    print(f"Checking {len(rules)} rules...")

    # Iterate over the list and collect names of rules that are
    # missing the log forwarding profile
    for rule in rules:
        if rule.log_setting != LOG_PROFILE:
            print(f"Found rule to configure: {rule.name}")
            rulebase.add(SecurityRule(rule.name, log_setting=LOG_PROFILE))

    # At this point, we've added SecurityRule objects to the Firewall
    # for each rule that doesn't have the right log forwarding profile.
    # The next step is to push all that configuration to the live device
    # at once using the 'create_similar()' method.

    # This takes the first SecurityRule to change and calls 'create_similar()'.
    # When 'create_similar()' is called, all the SecurityRules are pushed
    # to the firewall at once. The method is additive, so the existing security
    # rules will not change, except for the 'log_setting' parameter which
    # contains the log forwarding profile name.
    if len(rulebase.children) == 0:
        print("No changes needed")
        return

    rulebase.children[0].create_similar()

    # Now, trigger a commit
    # In this case, we'll wait for the commit to finish and trigger an exception
    # if the commit finished with any errors.
    print("Starting commit")
    fw.commit(sync=True, exception=True)
    print("Commit finished successfully")
Exemplo n.º 5
0
def firewall_export(export_fw, group, export_username, export_password):
    start = datetime.datetime.now()
    export_dict = {
        'groups': [],
        'addresses': []
    }  #To save data from the recursive function(s)
    pulling_fw = Firewall(export_fw, export_username,
                          export_password)  # Create a firewall object
    AddressObject.refreshall(
        pulling_fw)  #pulls down the address objects in the firewall
    AddressGroup.refreshall(
        pulling_fw, add=True)  # pulls down the address groups in the firewall
    top_level_group = pulling_fw.find(group)
    #recursively search for all entries inside the requested group digging out any nested groups

    recursive_group_search(group, pulling_fw, export_dict)
    export_dict['groups'].append(top_level_group.about())
    print(
        f"Exported {len(export_dict['addresses'])} address objects and {len(export_dict['groups'])} from { export_fw }"
    )
    print(f"took: {datetime.datetime.now() - start}")

    return export_dict
Exemplo n.º 6
0
    def get_pandevice_parent(self, module, timeout=0):
        """Builds the pandevice object tree, returning the parent object.

        If pandevice is not installed, then module.fail_json() will be
        invoked.

        Arguments:
            * module(AnsibleModule): the ansible module.
            * timeout(int): Number of seconds to retry opening the connection to PAN-OS.

        Returns:
            * The parent pandevice object based on the spec given to
              get_connection().
        """
        # Sanity check.
        if not HAS_PANDEVICE:
            module.fail_json(msg='Missing required library "pandevice".')

        pdv = tuple(int(x) for x in panos.__version__.split("."))

        # Inform people that they should upgrade to pan-os-python instead of pandevice.
        if pdv < (1, 0, 0):
            lum = [
                'Python library "pandevice" is now "pan-os-python" and is now 1.0!',
                'Please "pip install pan-os-python" at your earliest convenience.',
            ]
            module.deprecate(" ".join(lum),
                             version="3.0.0",
                             collection_name="paloaltonetworks.panos")

        # Verify pandevice minimum version.
        if self.min_pandevice_version is not None:
            if pdv < self.min_pandevice_version:
                module.fail_json(msg=_MIN_VERSION_ERROR.format(
                    "panos", panos.__version__,
                    _vstr(self.min_pandevice_version)))

        pan_device_auth, serial_number = None, None
        if module.params["provider"] and module.params["provider"][
                "ip_address"]:
            pan_device_auth = (
                module.params["provider"]["ip_address"],
                module.params["provider"]["username"],
                module.params["provider"]["password"],
                module.params["provider"]["api_key"],
                module.params["provider"]["port"],
            )
            serial_number = module.params["provider"]["serial_number"]
        elif module.params.get("ip_address", None) is not None:
            pan_device_auth = (
                module.params["ip_address"],
                module.params["username"],
                module.params["password"],
                module.params["api_key"],
                module.params["port"],
            )
            msg = 'Classic provider params are deprecated; use "provider" instead'
            module.deprecate(msg,
                             version="3.0.0",
                             collection_name="paloaltonetworks.panos")
        else:
            module.fail_json(msg="Provider params are required.")

        # Create the connection object.
        if not isinstance(timeout, int):
            raise ValueError("Timeout must be an int")
        elif timeout < 0:
            raise ValueError("Timeout must greater than or equal to 0")
        end_time = time.time() + timeout
        while True:
            try:
                self.device = PanDevice.create_from_device(*pan_device_auth)
            except PanDeviceError as e:
                if timeout == 0:
                    module.fail_json(msg="Failed connection: {0}".format(e))
                elif time.time() >= end_time:
                    module.fail_json(msg="Connection timeout: {0}".format(e))
            else:
                break

        # Verify PAN-OS minimum version.
        if self.min_panos_version is not None:
            if self.device._version_info < self.min_panos_version:
                module.fail_json(msg=_MIN_VERSION_ERROR.format(
                    "PAN-OS",
                    _vstr(self.device._version_info),
                    _vstr(self.min_panos_version),
                ))

        # Optional: Firewall via Panorama connectivity specified.
        if hasattr(self.device, "refresh_devices") and serial_number:
            fw = Firewall(serial=serial_number)
            self.device.add(fw)
            self.device = fw

        parent = self.device
        no_shared = 'Scope "shared" is not allowed'
        not_found = '{0} "{1}" is not present.'
        pano_mia_param = 'Param "{0}" is required for Panorama but not specified.'
        ts_error = "Specify either the template or the template stack{0}."
        if hasattr(self.device, "refresh_devices"):
            # Panorama connection.
            templated = False

            # Error if Panorama is not supported.
            if self.panorama_error is not None:
                module.fail_json(msg=self.panorama_error)

            # Spec: template stack.
            tmpl_required = False
            added_template = False
            if self.template_stack is not None:
                name = module.params[self.template_stack]
                if name is not None:
                    templated = True
                    stacks = TemplateStack.refreshall(parent, name_only=True)
                    for ts in stacks:
                        if ts.name == name:
                            parent = ts
                            added_template = True
                            break
                    else:
                        module.fail_json(msg=not_found.format(
                            "Template stack",
                            name,
                        ))
                elif self.template is not None:
                    tmpl_required = True
                elif not self.template_is_optional:
                    module.fail_json(
                        msg=pano_mia_param.format(self.template_stack))

            # Spec: template.
            if self.template is not None:
                name = module.params[self.template]
                if name is not None:
                    templated = True
                    if added_template:
                        module.fail_json(msg=ts_error.format(", not both"))
                    templates = Template.refreshall(parent, name_only=True)
                    for t in templates:
                        if t.name == name:
                            parent = t
                            break
                    else:
                        module.fail_json(msg=not_found.format(
                            "Template",
                            name,
                        ))
                elif self.template_is_optional:
                    pass
                elif tmpl_required:
                    module.fail_json(msg=ts_error.format(""))
                elif not added_template:
                    module.fail_json(msg=pano_mia_param.format(self.template))

            # Spec: vsys_dg or device_group.
            dg_name = self.vsys_dg or self.device_group
            if dg_name is not None:
                name = module.params[dg_name]
                if name not in (None, "shared"):
                    groups = DeviceGroup.refreshall(parent, name_only=True)
                    for dg in groups:
                        if dg.name == name:
                            parent = dg
                            break
                    else:
                        module.fail_json(msg=not_found.format(
                            "Device group",
                            name,
                        ))

            # Spec: vsys importable.
            vsys_name = self.vsys_importable or self.vsys or self.vsys_shared
            if dg_name is None and templated and vsys_name is not None:
                name = module.params[vsys_name]
                if name not in (None, "shared"):
                    vo = Vsys(name)
                    parent.add(vo)
                    parent = vo

            # Spec: rulebase.
            if self.rulebase is not None:
                if module.params[self.rulebase] in (None, "pre-rulebase"):
                    rb = PreRulebase()
                    parent.add(rb)
                    parent = rb
                elif module.params[self.rulebase] == "rulebase":
                    rb = Rulebase()
                    parent.add(rb)
                    parent = rb
                elif module.params[self.rulebase] == "post-rulebase":
                    rb = PostRulebase()
                    parent.add(rb)
                    parent = rb
                else:
                    module.fail_json(msg=not_found.format(
                        "Rulebase", module.params[self.rulebase]))
        else:
            # Firewall connection.
            # Error if firewalls are not supported.
            if self.firewall_error is not None:
                module.fail_json(msg=self.firewall_error)

            # Spec: vsys or vsys_dg or vsys_importable.
            vsys_name = (self.vsys_dg or self.vsys or self.vsys_importable
                         or self.vsys_shared)
            if vsys_name is not None:
                parent.vsys = module.params[vsys_name]
                if parent.vsys == "shared" and self.error_on_firewall_shared:
                    module.fail_json(msg=no_shared)

            # Spec: rulebase.
            if self.rulebase is not None:
                rb = Rulebase()
                parent.add(rb)
                parent = rb

        # If the module has the commit option set, show a deprecation warning.
        if module.params.get("commit"):
            module.deprecate(
                "Please use the commit modules instead of the commit option",
                version="3.0.0",
                collection_name="paloaltonetworks.panos",
            )

        # Done.
        return parent
Exemplo n.º 7
0
def _fw():
    fw = Firewall("127.0.0.1", "admin", "admin", "secret")
    fw._version_info = (9999, 0, 0)
    return fw
Exemplo n.º 8
0
from prtg.sensor.result import CustomSensorResult
from prtg.sensor.units import ValueUnit
import lxml.etree as ET
logging.basicConfig(
    filename="Power_supply_sensor_debug.log",
    filemode='a',
    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
    datefmt='%Y:%M:%D:%H:%M:%S',
    level=logging.INFO)
if __name__ == "__main__":
    try:
        data = json.loads(sys.argv[1])
        username = data['linuxloginusername']
        passwd = data['linuxloginpassword']
        host = data['host']
        fw = Firewall(host, api_username=username, api_password=passwd)
        env_info = fw.op("show system environmentals", xml=True)
        env_decode = env_info.decode("utf-8")
        tree = ET.fromstring(str(env_decode))
        ps_items = tree.xpath(".//power-supply/Slot1/entry/description")
        ps_status_list = []
        for ps_item in ps_items:
            ps_status = []
            ps_des = ''.join(ps_item.itertext())
            ps_status.append(ps_des)
            for sb_item in ps_item.itersiblings(preceding=True):
                ps_status.append(sb_item.text)
            ps_status_list.append(ps_status)
        num_ps_found = len(ps_status_list)

        csr = CustomSensorResult(