How to Monitor Network Bandwidth on Ubuntu using Shell Scripts
Why Your Network Needs a Speed Camera
Ever get slapped with a massive cloud provider bill because some rogue process decided to download half the internet at 3 AM? Yeah. It hurts. You think your server is just chilling, but underneath, your bandwidth is getting hammered. You need visibility. Not some bloated enterprise software that takes three days to configure and a dedicated database. Just a simple, dirty, effective shell script running on your Ubuntu box. You need a bandwidth monitor bash setup that actually works.
vnStat: The Silent Watcher
You can't write a script without a way to actually track the data. Enter vnStat. It’s lightweight. It doesn't sniff your actual packet payloads, so it won't melt your CPU. It just keeps a neat, running tally of what goes in and what goes out. Run a quick `sudo apt install vnstat` on your Ubuntu machine. Give it a minute to gather its first data points. Now you've got the engine for your ubuntu vnstat script. No fuss. Just pure, logged metrics waiting to be read.
Extracting the Dirt with Bash
Time to get our hands dirty. We are going to extract the exact numbers we need. vnStat spits out a lot of text, but we only care about the daily total. Using a mix of `grep` and `awk`, you can slice that terminal output down to a single raw number. Here's the thing. You want your script to run as a cron job, waking up every hour, checking the stats, and going back to sleep. We aren't building a constantly running daemon. We're building a highly efficient hit-and-run script.
Rigging the Panic Button
Logging data is completely useless if you never look at it. We need a network traffic alert that screams at you when you cross a threshold. Say your daily limit is 50GB. Once your bash script sees 45GB, it needs to fire off a warning. You can pipe this alert straight to a Discord webhook, Slack, or just a plain old email. A few lines of `curl` strapped to an `if` statement, and you instantly know when your server starts getting aggressively chatty. No more surprise invoices.