Skip to content

Instantly share code, notes, and snippets.

@djoreilly
Last active October 10, 2023 18:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save djoreilly/57ef65723bc8ad7ecdb899c5b8aaca47 to your computer and use it in GitHub Desktop.
Save djoreilly/57ef65723bc8ad7ecdb899c5b8aaca47 to your computer and use it in GitHub Desktop.
Pretty print iptables output. Align columns and strip out comments.
#!/usr/bin/python3
import re
import sys
from tabulate import tabulate
comments_re = re.compile(r'/\*.*\/')
in_chain, eof = False, False
headers, table = [], []
while True:
line = sys.stdin.readline()
if len(line) == 0:
eof = True
line = line.strip()
if line == '':
if in_chain:
headers.append('extra')
print(tabulate(table, headers=headers))
headers, table = [], []
in_chain = False
if eof:
break
continue
if line.startswith('Chain'):
print('\n{}'.format(line))
continue
if line.startswith('pkts') or line.startswith('target'):
headers = line.split()
in_chain = True
continue
if in_chain:
parts = line.split()
begin = parts[:len(headers)]
extra = ' '.join(parts[len(headers):])
# comments are too wide and usually redundant - strip out
extra = comments_re.sub('', extra)
table.append(begin + [extra])
$ sudo iptables -t nat -nL KUBE-NODEPORTS
Chain KUBE-NODEPORTS (1 references)
target prot opt source destination
KUBE-MARK-MASQ tcp -- 0.0.0.0/0 0.0.0.0/0 /* kube-system/traefik:http */ tcp dpt:31922
KUBE-SVC-X3WUOHPTYIG7AA3Q tcp -- 0.0.0.0/0 0.0.0.0/0 /* kube-system/traefik:http */ tcp dpt:31922
KUBE-MARK-MASQ tcp -- 0.0.0.0/0 0.0.0.0/0 /* kube-system/traefik:https */ tcp dpt:31783
KUBE-SVC-IKNZCF5XJQBTG3KZ tcp -- 0.0.0.0/0 0.0.0.0/0 /* kube-system/traefik:https */ tcp dpt:31783
$ sudo iptables -t nat -nL KUBE-NODEPORTS | ./pp-iptables.py
Chain KUBE-NODEPORTS (1 references)
target prot opt source destination extra
------------------------- ------ ----- --------- ------------- -------------
KUBE-MARK-MASQ tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:31922
KUBE-SVC-X3WUOHPTYIG7AA3Q tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:31922
KUBE-MARK-MASQ tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:31783
KUBE-SVC-IKNZCF5XJQBTG3KZ tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:31783
@intijk
Copy link

intijk commented Oct 22, 2022

--line-numbers not processed correctly, I did some tiny improvement.

https://gist.github.com/intijk/61a72d4445152048abb2802a87ec06bc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment