Here’s a script to do it for you:
#!/usr/bin/env python3
import subprocess
import sys
def add_networks_to_set(set_name, filename, batch_size=1000):
table_name = "vyos_filter" # Fixed table name
try:
with open(filename, 'r') as file:
networks = [line.strip() for line in file if line.strip()]
for i in range(0, len(networks), batch_size):
batch_networks = networks[i:i+batch_size]
networks_string = ', '.join(batch_networks)
command = f"nft add element ip {table_name} {set_name} {{ {networks_string} }}"
subprocess.run(command, check=True, shell=True)
print(f"Successfully added batch of networks to {set_name}")
except subprocess.CalledProcessError as e:
print(f"Error adding networks to {set_name}: {e}")
except FileNotFoundError:
print(f"File {filename} not found")
except Exception as e:
print(f"An error occurred: {e}")
def main():
if len(sys.argv) != 3:
print("Usage: python3 test.py <set name> <filename>")
sys.exit(1)
set_name = sys.argv[1]
filename = sys.argv[2]
add_networks_to_set(set_name, filename)
if __name__ == "__main__":
main()
Here’s how to use it:
- Create a group:
vyos@Hub# set firewall group network-group TEST
vyos@Hub# commit
- Verify group name as a nftables set:
root@Hub:/home/vyos# sudo nft list table ip vyos_filter
table ip vyos_filter {
set N_TEST {
type ipv4_addr
flags interval
auto-merge
}
chain VYOS_FORWARD_filter {
type filter hook forward priority filter; policy accept;
counter packets 0 bytes 0 accept comment "FWD-filter default-action accept"
}
chain VYOS_INPUT_filter {
type filter hook input priority filter; policy accept;
counter packets 36 bytes 3641 accept comment "INP-filter default-action accept"
}
chain VYOS_OUTPUT_filter {
type filter hook output priority filter; policy accept;
counter packets 29 bytes 2932 accept comment "OUT-filter default-action accept"
}
chain VYOS_FRAG_MARK {
type filter hook prerouting priority -450; policy accept;
ip frag-off & 16383 != 0 meta mark set 0x000ffff1 return
}
}
You can see our set is called N_TEST
- Run the script in this format: python3 <name of script> <name of set> <name of file>
root@Hub:/home/vyos# python3 test.py N_TEST iplist.txt
Successfully added 192.168.1.0/24 to N_TEST
Successfully added 10.0.0.0/8 to N_TEST
Successfully added 172.16.0.0/12 to N_TEST
- Verify:
root@Hub:/home/vyos# sudo nft list set ip vyos_filter N_TEST
table ip vyos_filter {
set N_TEST {
type ipv4_addr
flags interval
auto-merge
elements = { 10.0.0.0/8, 172.16.0.0/12,
192.168.1.0/24 }
}
}