diff options
author | Christian Poessinger <christian@poessinger.com> | 2021-02-14 18:20:48 +0100 |
---|---|---|
committer | Christian Poessinger <christian@poessinger.com> | 2021-02-14 18:20:51 +0100 |
commit | 9756e54926af81b48bc579c7de16b602cc54efcc (patch) | |
tree | 80edd66d62270dc01323d61af0a034b49bee9bb7 /python/vyos/template.py | |
parent | b4cda54afdabc8026458e4598272f93749005978 (diff) | |
download | vyos-1x-9756e54926af81b48bc579c7de16b602cc54efcc.tar.gz vyos-1x-9756e54926af81b48bc579c7de16b602cc54efcc.zip |
template: T2947: backport additional Jinja2 filters
is_ip_network and compare_netmask Jinja2 filter have been added via commit
920789798 ("nat: T2947: add many-many translation") on "current" and are
required for the 1:1 NAT functionality.
jinja2.exceptions.TemplateAssertionError: no filter named 'is_ip_network'
Diffstat (limited to 'python/vyos/template.py')
-rw-r--r-- | python/vyos/template.py | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/python/vyos/template.py b/python/vyos/template.py index bf087c223..527384d0b 100644 --- a/python/vyos/template.py +++ b/python/vyos/template.py @@ -149,7 +149,9 @@ def netmask_from_ipv4(address): Example: - 172.18.201.10 -> 255.255.255.128 """ - from netifaces import interfaces, ifaddresses, AF_INET + from netifaces import interfaces + from netifaces import ifaddresses + from netifaces import AF_INET for interface in interfaces(): tmp = ifaddresses(interface) if AF_INET in tmp: @@ -160,6 +162,30 @@ def netmask_from_ipv4(address): raise ValueError +@register_filter('is_ip_network') +def is_ip_network(addr): + """ Take IP(v4/v6) address and validate if the passed argument is a network + or a host address. + + Example: + - 192.0.2.0 -> False + - 192.0.2.10/24 -> False + - 192.0.2.0/24 -> True + - 2001:db8:: -> False + - 2001:db8::100 -> False + - 2001:db8::/48 -> True + - 2001:db8:1000::/64 -> True + """ + try: + from ipaddress import ip_network + # input variables must contain a / to indicate its CIDR notation + if len(addr.split('/')) != 2: + raise ValueError() + ip_network(addr) + return True + except: + return False + @register_filter('network_from_ipv4') def network_from_ipv4(address): """ Take IP address and search all attached interface IP addresses for the @@ -248,6 +274,21 @@ def dec_ip(address, decrement): from ipaddress import ip_interface return str(ip_interface(address).ip - int(decrement)) +@register_filter('compare_netmask') +def compare_netmask(netmask1, netmask2): + """ + Compare two IP netmask if they have the exact same size. + + compare_netmask('10.0.0.0/8', '20.0.0.0/8') -> True + compare_netmask('10.0.0.0/8', '20.0.0.0/16') -> False + """ + from ipaddress import ip_network + try: + return ip_network(netmask1).netmask == ip_network(netmask2).netmask + except: + return False + + @register_filter('isc_static_route') def isc_static_route(subnet, router): # https://ercpe.de/blog/pushing-static-routes-with-isc-dhcp-server |