Validate a prefix in an custom script

Skip to first unread message

Mats Brorson

Jun 1, 2021, 3:30:32 AMJun 1
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 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

Jun 1, 2021, 5:59:41 AMJun 1
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
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(
        self.log_success("Created prefix %s" % prefix.prefix)



Mats Brorson

Jun 1, 2021, 6:22:31 AMJun 1
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, as that gives an exception:

'psycopg2.errors.InvalidTextRepresentation: invalid cidr value: ""'

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

Jun 1, 2021, 7:00:33 AMJun 1
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("")
>>> == n.ip
>>> n.value == n.first
>>> m = netaddr.IPNetwork("")
>>> == m.ip
>>> m.value == m.first

Mats Brorson

Jun 1, 2021, 2:35:35 PMJun 1
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
0 new messages