1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
| tee /config/scripts/add-firewall-group.py << "EOF"
#!/usr/bin/env python3
import subprocess
import sys
import time
def add_networks_in_batches(set_name, filename, batch_size=1000):
#table_name = "vyos_filter" # Fixed table name
table_names = ["vyos_filter", "vyos_mangle", "vyos_nat", "vyos_conntrack"]
total_added = 0 # Initialize counter for total added IPs
start_time = time.time() # Record the start time
try:
with open(filename, 'r') as file:
networks = [line.strip() for line in file if line.strip()]
for table_name in table_names:
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}")
total_added += len(batch_networks) # Update count of added IPs
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}")
end_time = time.time() # Record the end time
elapsed_time = end_time - start_time # Calculate elapsed time
# Print summary
print(f"\nTotal of {total_added} networks were added to {set_name}.")
print(f"Process took {elapsed_time:.2f} seconds.")
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_in_batches(set_name, filename)
if __name__ == "__main__":
main()
EOF
|