All iptables rules list
This script is written in Python and it’s used to export the current iptables rules of a host machine, parse them into a CSV file, and then transfer that CSV file to a specified destination IP. After the transfer, it removes the local CSV file and the iptables rules file.
Script assumes the user used on the system has passwordless access to sudo.
Here’s a step-by-step breakdown of what the script does:
1. Get the host IP and current user
The script first retrieves the host IP and the username of the current user. This is done using the subprocess.getoutput
and getpass.getuser
functions, respectively.
host_ip = subprocess.getoutput("hostname -I | awk '{print $1}'")
username = getpass.getuser()
2. Ask for the destination IP
The script prompts the user to enter the destination IP where the CSV file will be transferred.
destination_ip = input("Please enter the destination IP: ")
3. Save iptables rules to a file
The script saves the current iptables rules to a file located in the home directory of the current user. This is done using the iptables-save
command.
iptables_file_path = f'/home/{username}/iptables-rules.v4'
with open(iptables_file_path, 'w') as f:
subprocess.run(['sudo', 'iptables-save'], stdout=f)
4. Change the permissions of the iptables rules file
The script changes the permissions of the iptables rules file to 666 (read and write permissions for all users) using the os.chmod
function.
os.chmod(iptables_file_path, 0o666)
5. Parse the saved rules and write to a CSV file
The script reads the iptables rules file, parses the rules, and writes them to a CSV file. It uses the csv.DictWriter
class to write the rules to the CSV file.
csv_file_path = f'/home/{username}/{host_ip}.csv'
with open(iptables_file_path, 'r') as f, open(csv_file_path, 'w', newline='') as csvfile:
# ... code to parse the rules and write to the CSV file ...
6. Change the permissions of the CSV file
The script changes the permissions of the CSV file to 666 (read and write permissions for all users) using the os.chmod function.
os.chmod(csv_file_path, 0o666)
7. Transfer the CSV file to the specified IP
The script transfers the CSV file to the specified destination IP using the scp command. It uses ssh agent forwarding and disables strict host key checking for this operation.
scp_command = f"scp -o ForwardAgent=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null {csv_file_path} {username}@{destination_ip}:/home/{username}"
scp_result = subprocess.run(scp_command, shell=True, capture_output=True, text=True)
8. Remove the local CSV file and iptables rules file
Finally, the script removes the local CSV file and the iptables rules file using the sudo rm -rf command.
os.system(f'sudo rm -rf {csv_file_path}')
os.system(f'sudo rm -rf {iptables_file_path}')
Please note that the output of this script will vary depending on the iptables rules of the host machine and the destination IP provided by the user. Also, please be careful when using sudo rm -rf as it can permanently delete files. Make sure the paths are correct before running the script. Also, note that this operation might require the user’s password for sudo access. If the script is intended to be run without interaction, you might need to configure sudo to not require a password for these specific commands. Please consult your system administrator or the appropriate documentation for instructions on how to do this. It’s important to ensure that such changes to sudo
configuration are done securely.
In order to get this script, copy the content of the field below and paste it into a file with a .py extension in your preferred location, using any text editor. Save the file and run it using python3 script_name.py
import csv
import os
import re
import subprocess
import getpass
# Get the host IP
host_ip = subprocess.getoutput("hostname -I | awk '{print $1}'")
# Get the current user
username = getpass.getuser()
# Ask for the destination IP
destination_ip = input("Please enter the destination IP: ")
# Save iptables rules to a file
iptables_file_path = f'/home/{username}/iptables-rules.v4'
with open(iptables_file_path, 'w') as f:
subprocess.run(['sudo', 'iptables-save'], stdout=f)
print(f"Successfully exported iptables rules to {iptables_file_path}")
# Change the permissions of the iptables rules file
os.chmod(iptables_file_path, 0o666)
print(f"Successfully changed permissions of iptables rules file at {iptables_file_path}")
# Parse the saved rules and write to a CSV file
csv_file_path = f'/home/{username}/{host_ip}.csv'
with open(iptables_file_path, 'r') as f, open(csv_file_path, 'w', newline='') as csvfile:
fieldnames = ['host_ip', 'table', 'chain', 'source_port', 'source_ip', 'dest_port', 'return', 'target']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
table = ''
for line in f:
if line.startswith('*'):
table = line[1:-1]
elif line.startswith(':'):
chain, target, _ = line[1:].split()
writer.writerow({'host_ip': host_ip, 'table': table, 'chain': chain, 'target': target})
elif line.startswith('-A'):
parts = line.split()
chain = parts[1]
source_ip = parts[parts.index('-s')+1] if '-s' in parts else ''
source_port = parts[parts.index('-p')+1] if '-p' in parts else ''
dest_port = parts[parts.index('--dport')+1] if '--dport' in parts else ''
return_state = parts[parts.index('--ctstate')+1] if '--ctstate' in parts else ''
target = parts[-1]
writer.writerow({'host_ip': host_ip, 'table': table, 'chain': chain, 'source_port': source_port, 'source_ip': source_ip, 'dest_port': dest_port, 'return': return_state, 'target': target})
print(f"Successfully parsed iptables rules into CSV file at {csv_file_path}")
# Change the permissions of the CSV file
os.chmod(csv_file_path, 0o666)
print(f"Successfully changed permissions of CSV file at {csv_file_path}")
# Transfer the CSV file to the specified IP using scp with ssh agent forwarding
scp_command = f"scp -o ForwardAgent=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null {csv_file_path} {username}@{destination_ip}:/home/{username}"
scp_result = subprocess.run(scp_command, shell=True, capture_output=True, text=True)
print(f"Successfully transferred CSV file to {destination_ip}")
# Remove the local CSV file
os.system(f'sudo rm -rf {csv_file_path}')
print(f"Successfully removed the local CSV file at {csv_file_path}")
# Remove the local iptables rules file
os.system(f'sudo rm -rf {iptables_file_path}')
print(f"Successfully removed the processed iptables rules file at {iptables_file_path}")