#!/usr/bin/perl use strict; my $want_install; if (@ARGV && $ARGV[0] eq "--install") { shift @ARGV; $want_install = 1; } my $rulecount = 0; my %inpackets; my %inbytes; my %outpackets; my %outbytes; my $ipreg = "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"; my $chain; for (`iptables -L -n -v -x`) { ++$rulecount; chomp; if (/^Chain (\S+)/) { $chain = $1; } my ($pkts, $bytes, $prot, $opt, $in, $out, $source, $dest) = split; if ($pkts !~ /\D/ && $bytes !~ /\D/ && $prot eq "all" && $opt eq "--") { if ($in eq "eth+" && $out eq "*" && $source eq "0.0.0.0/0" && $dest =~ /^$ipreg$/) { $inpackets{$dest} = $pkts; $inbytes{$dest} = $bytes; } elsif ($out eq "eth+" && $in eq "*" && $dest eq "0.0.0.0/0" && $source =~ /^$ipreg$/) { $outpackets{$source} = $pkts; $outbytes{$source} = $bytes; } } } if ($rulecount > 1000 && $want_install) { warn "You already have more than 1000 rules; I will add any more"; $want_install = 0; } for (`ifconfig`) { if (/\baddr:(\S+)/ && $1 ne "127.0.0.1") { if ($want_install) { print "iptables -I INPUT -d $1 -i eth+\n" if !defined $inbytes{$1}; print "iptables -I OUTPUT -s $1 -o eth+\n" if !defined $outbytes{$1}; } $inbytes{$1} ||= 0; $outbytes{$1} ||= 0; $inpackets{$1} ||= 0; $outpackets{$1} ||= 0; } } foreach (sort keys %outbytes) { print "$_ $inpackets{$_} $inbytes{$_} $outpackets{$_} $outbytes{$_}\n"; }