3

In my iptables log files (Ubuntu 16-04), all messages from my LAN router and from other hosts in the LAN, related to IGMP have "PROTO=2". Is there a way to change this and get "PROTO=IGMP"?

2
sed -e "$(awk '/^[[:space:]]*(#|$)/ { next } ;
               { print "s/ PROTO="$2" / PROTO="$3" /;" }' \
          /etc/protocols)" /path/to/iptables.log

This uses awk to construct a sed script from fields 2 and 3 of the /etc/protocols file. It then runs that sed script on /path/to/iptables.log. This will convert ALL numbered protocols in the log file to their corresponding names.

If you prefer, you could save the output of the awk script to a file (e.g. called verbose-proto.sed and then run it with sed -f (or even edit it to add #!/bin/sed -f as the first line and chmod it to make it executable). e.g.

$ awk '/^[[:space:]]*(#|$)/ { next } ;
     { print "s/ PROTO="$2" / PROTO="$3" /;" }' \
    /etc/protocols > ./verbose-proto.sed

$ printf "%s\n" 1 i '#!/bin/sed -f' . w | ed -s verbose-proto.sed
$ chmod +x ./verbose-proto.sed 
$ ./verbose-proto.sed /path/to/iptables.log

If all you want to do is change that one protocol number 2 to IGMP, it's much simpler:

sed -e 's/ PROTO=2 / PROTO=IGMP /' /path/to/iptables.log

(the awk script generates about 50 lines with regexp search and replace rules like this - one for each known protocol in /etc/protocols)

  • Magic! I was expecting some setting in iptables configuration that would achieve this. It never crossed my mind writing a script that would look into /etc/protocols to dynamically construct and run a sed script able to do all substitutions. I had heard about awk, but this really shows its powers. Thank you for sharing this ingenious solution. – ARX May 1 '16 at 23:27
  • no problem, it made the question more interesting for me to answer than just the single 2-->IGMP solution :). BTW, i think of it more as showing off the power of shell than awk. The awk and sed scripts themselves are fairly simple examples of what those tools can do....it's the shell's ability to combine multiple tools with pipelines and command substitution that's really powerful. – cas May 1 '16 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.