Validate a prefix in an custom script

344 views
Skip to first unread message

Mats Brorson

unread,
Jun 1, 2021, 3:30:32 AM6/1/21
to NetBox
We often need to import data from external systems, where we have networks added manually, and we know that some of these are invalid ones (fex 172.10.1.13/26) and would like to do a validation, and if it fails place an notification to owner of that particular network to update incorrect values.

I thought it was as simple as trying to create an IPNetworkVar() with the incorrect prefix, and it will give an error, as ther are som validation in place in the UI. This however happily accept the incorrect prefix.

How would I do this validation?

Brian Candler

unread,
Jun 1, 2021, 5:59:41 AM6/1/21
to NetBox
What Netbox version? What's your code?

It all works fine for me with Netbox v2.11.4.  Script:

root@netbox:/opt/netbox/netbox/scripts# cat create_prefix.py
from ipam.models import Prefix
from extras.scripts import Script, IPNetworkVar

class NewPrefix(Script):
    class Meta:
        name = "New Prefix"
        description = "Create a new prefix "
        field_order = ['prefix']

    prefix = IPNetworkVar(label="Prefix")

    def run(self, data, commit):
        prefix = Prefix(
            prefix=data["prefix"],
        )
        prefix.save()
        self.log_success("Created prefix %s" % prefix.prefix)

Results:

image1.png

Mats Brorson

unread,
Jun 1, 2021, 6:22:31 AM6/1/21
to NetBox
Netbox v2.10.10

But I'm not using the input form for validation. When I execute my script, I do a rest call to an endpoint that gives me a list of prefixes. I then iterate over that list, and I would like to validate before creating and do a prefix.save(), as that gives an exception:

'psycopg2.errors.InvalidTextRepresentation: invalid cidr value: "192.168.1.1/24"'

Of course I could handle the exception, but if there was an easy way of validating before creating the Prefix object, ot would be nice.

Brian Candler

unread,
Jun 1, 2021, 7:00:33 AM6/1/21
to NetBox
IPNetworkVar is a GUI widget, it's not useful for accessing the REST API.

You can always validate the network in your python code before making the REST call.  One way is using netaddr:

>>> import netaddr
>>> n = netaddr.IPNetwork("192.168.1.1/24")
>>> n.network == n.ip
False
>>> n.value == n.first
False
>>> m = netaddr.IPNetwork("192.168.1.0/24")
>>> m.network == m.ip
True
>>> m.value == m.first
True

Mats Brorson

unread,
Jun 1, 2021, 2:35:35 PM6/1/21
to NetBox
Brian, you are an hero. Completely missed that netaddr library was there. Learning new stuff every day.

Now I have an working solution cutting lines of code to a Zen Of Python level:-)

Reply all
Reply to author
Forward
0 new messages