Beispiel #1
0
class NetworkScanResult(BaseSchema):
    start = DateTime(description="When the scan started")
    end = DateTime(
        description="When the scan finished. Will be Null if not yet run.",
        allow_none=True,
    )
    state = String(
        description="Last scan result",
        enum=[
            "not_started",
            "running",
            "succeeded",
            "failed",
        ],
    )
Beispiel #2
0
class IPNetwork(BaseSchema, CheckmkTuple):
    tuple_fields = ("type", "network")
    cast_to_dict = True

    type = _fields.Constant(
        description="A single IPv4 network in CIDR notation.",
        constant="ip_network",
    )
    network = String(
        description=(
            "A IPv4 network in CIDR notation. Minimum prefix length is 8 bit, "
            "maximum prefix length is 30 bit.\n\nValid examples:\n\n"
            " * `192.168.0.0/24`\n"
            " * `192.168.0.0/255.255.255.0`"),
        validate=ValidateIPv4Network(min_prefix=8, max_prefix=30),
    )
Beispiel #3
0
class IPAddresses(BaseSchema, CheckmkTuple):
    """Represents a list of IPv4 addresses

    >>> schema = IPAddresses()
    >>> rv = schema.dump(('ip_list', ['127.0.0.1', '127.0.0.2']))
    >>> rv
    {'type': 'ip_list', 'addresses': ['127.0.0.1', '127.0.0.2']}

    >>> schema.load(rv)
    ('ip_list', ['127.0.0.1', '127.0.0.2'])

    """
    tuple_fields = ('type', 'addresses')
    cast_to_dict = True

    type = _fields.Constant(
        description="A list of single IPv4 addresses.",
        constant='ip_list',
    )
    addresses = List(String(validate=ValidateIPv4(),))
Beispiel #4
0
class IPRegexp(BaseSchema, CheckmkTuple):
    """

    >>> schema = IPRegexp()
    >>> rv = schema.dump(('ip_regex_list', ['127.0.[0-9].1', '127.0.[0-9].2']))
    >>> schema.load(rv)
    ('ip_regex_list', ['127.0.[0-9].1', '127.0.[0-9].2'])

    """
    tuple_fields = ('type', 'regexp_list')
    cast_to_dict = True

    type = _fields.Constant(
        description="IPv4 addresses which match a regexp pattern",
        constant='ip_regex_list',
    )
    regexp_list = List(
        String(validate=IsValidRegexp()),
        description=("A list of regular expressions which are matched against the found "
                     "IP addresses. The matches will be excluded from the result."),
    )
Beispiel #5
0
class NetworkScan(BaseSchema):
    """

    >>> schema = NetworkScan()
    >>> settings = {
    ...     'exclude_ranges': [('ip_list', ['192.168.0.2']),
    ...                        ('ip_regex_list', ['192.168.[02].*'])],
    ...     'ip_ranges': [('ip_range', ('192.168.0.10', '192.168.0.244')),
    ...                   ('ip_regex_list', ['192.168.[01].*']),
    ...                   ('ip_list', ['192.168.0.2'])],
    ...     'max_parallel_pings': 100,
    ... #   This is disabled, due to "running outside app context", duh.
    ... #   'run_as': 'cmkadmin',
    ...     'scan_interval': 86400,
    ...     'set_ipaddress': True,
    ...     'time_allowed': [((12, 0), (23, 59))],
    ...     'translate_names': {
    ...         'case': 'lower',
    ...         'drop_domain': True,
    ...         'mapping': [('example.com', 'www.example.com')],
    ...         'regex': [('.*', 'mehrfacheregulaere')]}}
    >>> result = schema.dump(settings)
    >>> assert len(result['addresses']) == 3
    >>> assert len(result['exclude_addresses']) == 2
    >>> assert len(result['time_allowed'][0]) == 2
    >>> assert len(result['translate_names']) == 4

    >>> import unittest
    >>> test_case = unittest.TestCase()
    >>> test_case.maxDiff = None
    >>> test_case.assertDictEqual(settings, schema.load(result))

    """

    ip_ranges = List(
        Nested(IPRangeWithRegexp()),
        data_key="addresses",
        required=True,
        description="IPv4 addresses to include.",
    )
    exclude_ranges = List(
        Nested(IPRangeWithRegexp()),
        data_key="exclude_addresses",
        description="IPv4 addresses to exclude.",
    )
    scan_interval = Integer(
        description=
        "Scan interval in seconds. Default is 1 day, minimum is 1 hour.",
        missing=60 * 60 * 24,
        minimum=3600,
    )
    time_allowed = List(
        Nested(TimeAllowedRange()),
        description=
        "Only execute the discovery during this time range each day..",
        required=True,
    )
    set_ipaddress = _fields.Boolean(
        data_key="set_ip_address",
        description=
        "When set, the found IPv4 address is set on the discovered host.",
        missing=True,
    )
    max_parallel_pings = Integer(
        description=
        "Set the maximum number of concurrent pings sent to target IP addresses.",
        required=False,
        minimum=1,
        maximum=200,
        missing=100,
    )
    run_as = String(
        description=
        ("Execute the network scan in the Checkmk user context of the chosen user. "
         "This user needs the permission to add new hosts to this folder."),
        required=False,
        validate=_active_users,
    )
    translate_names = Nested(TranslateNames)
Beispiel #6
0
class RegexpRewrites(BaseSchema, CheckmkTuple):
    r"""Represents a regexp replacement.

    The replacement string gets validated against the regexp for match group compatibility.

    Examples:

        >>> schema = RegexpRewrites()
        >>> tup = schema.load({'search': '(abc)', 'replace_with': '\\1'})
        >>> tup
        ('(abc)', '\\1')

        >>> schema.dump(tup)
        {'search': '(abc)', 'replace_with': '\\1'}

        >>> schema.load({'search': 'abc', 'replace_with': '\\1, \\22'})  # doctest: +ELLIPSIS
        Traceback (most recent call last):
        ...
        m...: {'replace_with': ['regexp only contains 0 match groups, but a match group with index 22 (\\22) was used in the replacement string.']}

        >>> schema.load({'search': '()()()', 'replace_with': '\\1, \\3'})  # doctest: +ELLIPSIS
        ('()()()', '\\1, \\3')

    """
    tuple_fields = ("search", "replace_with")
    cast_to_dict = True

    search = String(
        description=
        ("The search regexp. May contain match-groups, conditional matches, etc. "
         "This follows the Python regular expression syntax.\n\n"
         "For details see:\n\n"
         " * https://docs.python.org/3/library/re.html"),
        maxLength=30,
        validate=IsValidRegexp(),
        required=True,
    )
    replace_with = String(
        description=
        "The replacement string. Match-groups can only be identified by `\\1`, `\\2`, "
        "etc. Highest supported match group is `\\99`. Named lookups are not "
        "supported.",
        maxLenth=30,
        required=True,
    )

    @validates_schema
    def validate_replacement(self, data, **kwargs):
        search = re.compile(data["search"])
        replace_groups = list(
            set(re.findall(r"\\((?:[1-9]|\d\d)+)", data["replace_with"])))
        replace_groups.sort()

        # NOTE
        # We don't need to check for exhaustive use of the replacement groups. We only need
        # to check the highest match-group used in the replacement, as this is the only case
        # where a mismatch may occur.
        if replace_groups:
            highest_replacement_group = int(replace_groups[-1])
            if highest_replacement_group > search.groups:
                raise ValidationError(
                    f"regexp only contains {search.groups} match groups, but a match group with "
                    f"index {highest_replacement_group} (\\{highest_replacement_group}) was used "
                    "in the replacement string.",
                    field_name="replace_with",
                )
Beispiel #7
0
        description="The hostname to be replaced.",
        required=True,
    )
    replace_with = _fields.String(
        description="The replacement string.",
        required=True,
    )


class TranslateNames(BaseSchema):
    case = String(
        data_key="convert_case",
        description=
        "Convert all detected hostnames to upper- or lower-case.\n\n" +
        _enum_options([
            ("nop", "Do not convert anything"),
            ("lower", "Convert all hostnames to lowercase."),
            ("upper", "Convert all hostnames to uppercase."),
        ]),
        enum=["nop", "lower", "upper"],
        missing="nop",
    )
    drop_domain = _fields.Boolean(description=(
        "Drop the rest of the domain, only keep the hostname. Will not affect "
        "IP addresses.\n\n"
        "Examples:\n\n"
        " * `192.168.0.1` -> `192.168.0.1`\n"
        " * `foobar.example.com` -> `foobar`\n"
        " * `example.com` -> `example`\n"
        " * `example` -> `example`\n\n"
        "This will be executed **after**:\n\n"
        " * `convert_case`\n"), )
Beispiel #8
0
class MetaData(BaseSchema):
    created_at = Timestamp(description="When has this object been created.",)
    updated_at = Timestamp(description="When this object was last changed.",)
    created_by = String(description="The user id under which this object has been created.",)
Beispiel #9
0
    hostname = _fields.String(
        description="The hostname to be replaced.",
        required=True,
    )
    replace_with = _fields.String(
        description="The replacement string.",
        required=True,
    )


class TranslateNames(BaseSchema):
    case = String(
        data_key='convert_case',
        description="Convert all detected hostnames to upper- or lower-case.\n\n" + _enum_options([
            ('nop', 'Do not convert anything'),
            ('lower', 'Convert all hostnames to lowercase.'),
            ('upper', 'Convert all hostnames to uppercase.'),
        ]),
        enum=['nop', 'lower', 'upper'],
        missing='nop',
    )
    drop_domain = _fields.Boolean(
        description=("Drop the rest of the domain, only keep the hostname. Will not affect "
                     "IP addresses.\n\n"
                     "Examples:\n\n"
                     " * `192.168.0.1` -> `192.168.0.1`\n"
                     " * `foobar.example.com` -> `foobar`\n"
                     " * `example.com` -> `example`\n"
                     " * `example` -> `example`\n\n"
                     "This will be executed **after**:\n\n"
                     " * `convert_case`\n"),)
    regex = List(
Beispiel #10
0
class IPMIParameters(BaseSchema):
    cast_to_dict = True

    username = String(required=True)
    password = String(required=True)