How to Save iftop Output to a Text File for Bandwidth Monitoring


2 views

iftop is an excellent real-time bandwidth monitoring tool that displays network usage by source/destination IPs and ports. However, its ncurses-based interface makes direct output redirection problematic:

iftop > bandwidth.log  # Produces unreadable binary data

Here are three reliable methods to capture iftop's output:

1. Using the -t Option

The simplest solution is iftop's built-in text mode:

iftop -t -P -n -N -s 60 > bandwidth.txt

Key flags:

-t: Text output mode

-P: Show ports

-n: Disable hostname resolution

-N: Show port numbers instead of services

-s 60: Run for 60 seconds

2. Capturing with Script

For more control, use a wrapper script:

#!/bin/bash
{
    echo "Starting iftop capture at $(date)"
    iftop -t -P -n -N 2>&1 | tee -a bandwidth.log
    echo "Capture completed at $(date)"
} >> bandwidth.log

3. Alternative Tools

If you need continuous logging, consider these alternatives:

nload:

nload -t 5000 -m -o " " -u K > traffic.log

vnStat (for long-term trends):

vnstat --dumpdb > vnstat_dump.txt

To process the captured data:

awk '/=>/ {print $2,$4,$5}' bandwidth.txt | sort -k3 -rn | head -10

This shows top 10 bandwidth consumers by destination.

For production systems, create a cron job:

*/5 * * * * /usr/sbin/iftop -t -P -n -N -s 300 >> /var/log/bandwidth/$(date +\%Y\%m\%d).log

iftop is an incredibly useful real-time bandwidth monitoring tool that displays network usage by source/destination IPs and ports. However, its ncurses-based interface makes direct output redirection problematic. When you try:

iftop > bandwidth.log

You'll get unreadable control characters in the output file because ncurses uses terminal control sequences for its display.

Method 1: Using the -t and -N Options

The cleanest native solution is to use iftop's built-in text output mode:

iftop -t -N -n -s 5 > bandwidth.log

Where:
-t : enables text output mode
-N : shows port numbers instead of service names
-n : disables DNS resolution (faster output)
-s 5 : runs for 5 seconds then exits

Method 2: Screen/Tmux Session Logging

For those needing the full visual output, you can use terminal multiplexers:

screen -L -Logfile bandwidth.log iftop
tmux new-session -s iftop-log 'script -q bandwidth.log -c iftop'

Method 3: Alternative Tools for Text Output

If you need continuous logging, consider these alternatives:

nethogs -t -d 5 > traffic_by_process.log
bwm-ng -o plain -F bandwidth.csv

For periodic bandwidth snapshots, create a cron job:

*/5 * * * * /usr/sbin/iftop -t -N -n -s 10 > /var/log/bandwidth/$(date +\%Y\%m\%d-\%H\%M).log

Here's a simple awk script to extract top talkers:

awk '/^[0-9]/{print $1,$2,$3,$4,$5,$6,$7}' bandwidth.log | sort -k7 -rn