Last active
October 22, 2020 08:42
-
-
Save wido/5115ba4eacb7e4eb962507140b78b498 to your computer and use it in GitHub Desktop.
Count IPv4 vs IPv6 traffic flowing over a Linux bridge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# | |
# I have a Linux machine between my ISP's router and my switch. Two interfaces | |
# are bridged so I can inspect all traffic coming in and going out. | |
# | |
# | |
# bridge name bridge id STP enabled interfaces | |
# br1 8000.8eb20d8d9b94 no enp0s20f0 | |
# enp0s20f1 | |
# | |
# | |
# iptables -I FORWARD -i br1 -o br1 -j ACCEPT | |
# ip6tables -I FORWARD -i br1 -o br1 -j ACCEPT | |
# | |
# Using this information I can create graphs of my IPv4 vs IPv6 traffic | |
# | |
# A systemd timer runs executes this script every 10 seconds | |
# | |
# Author: Wido den Hollander <[email protected]> | |
# | |
from subprocess import check_output, CalledProcessError | |
import datetime | |
from influxdb import InfluxDBClient | |
INFLUX_HOST = 'influxdb' | |
INFLUX_DB = 'traffic' | |
def execute(cmd): | |
return check_output(cmd, shell=True).decode() | |
def get_ip_stats(): | |
stats = {'ipv4': {}, 'ipv6': {}} | |
ipv4 = execute('iptables -L -Z -v -x -n --line-numbers|grep ^1|grep br1').split() | |
ipv6 = execute('ip6tables -L -Z -v -x -n --line-numbers|grep ^1|grep br1').split() | |
stats['ipv4']['packets'] = int(ipv4[1]) | |
stats['ipv4']['bytes'] = int(ipv4[2]) | |
stats['ipv6']['packets'] = int(ipv6[1]) | |
stats['ipv6']['bytes'] = int(ipv6[2]) | |
return stats | |
stats = get_ip_stats() | |
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat() | |
measurements = [ | |
{ | |
'measurement': 'ip_traffic', | |
'time': now, | |
'fields': { | |
'packets': stats['ipv4']['packets'], | |
'bytes': stats['ipv4']['bytes'], | |
}, | |
'tags': { | |
'family': 4 | |
} | |
}, | |
{ | |
'measurement': 'ip_traffic', | |
'time': now, | |
'fields': { | |
'packets': stats['ipv6']['packets'], | |
'bytes': stats['ipv6']['bytes'] | |
}, | |
'tags': { | |
'family': 6 | |
} | |
} | |
] | |
client = InfluxDBClient(host=INFLUX_HOST, database=INFLUX_DB) | |
client.write_points(measurements) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment