Last active 1731231225

Revision edb15c833e4b1ee98c19a9a0187fd5ff7484679c

MoniTraffic.sh Raw
1#!/bin/bash
2
3function monitor_traffic() {
4 if [ -z "$1" ]; then
5 echo "Usage: $0 <network_interface>"
6 echo "Available network interfaces:"
7 ip link show | awk -F': ' '/^[0-9]+: /{print $2}'
8 exit 1
9 fi
10
11 INTERFACE=$1
12 DURATION=10 # Duration in seconds for each capture window
13
14 # Output header only once
15 printf "IP Address\tDownload (bytes)\tUpload (bytes)\n"
16
17 # Handle SIGINT (Ctrl+C) to gracefully exit the loop
18 trap "echo 'Exiting...'; exit 0" SIGINT
19
20 while true; do
21 # Temp file to store tcpdump output
22 TMP_FILE=$(mktemp)
23 trap "rm -f $TMP_FILE" EXIT # Ensure cleanup on exit or interruption
24
25 # Capture IPv4 traffic on the specified interface for the specified duration
26 sudo timeout $DURATION tcpdump -i $INTERFACE -nn -q -tt 'ip' > $TMP_FILE 2>/dev/null
27
28 # Calculate traffic statistics
29 awk '
30 /IP/ {
31 # Extract source and destination IPs using a stricter pattern to ensure only IPs are captured
32 if (match($3, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) {
33 src_ip = substr($3, RSTART, RLENGTH)
34 }
35 if (match($5, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) {
36 dst_ip = substr($5, RSTART, RLENGTH)
37 }
38
39 # Calculate packet size (bytes) - field 8 (better validation)
40 size = $NF
41 if (size ~ /^[0-9]+$/) {
42 # Count download (dst_ip) and upload (src_ip) for traffic
43 download[dst_ip] += size
44 upload[src_ip] += size
45 }
46 }
47 END {
48 # Create a combined total_bytes array for sorting
49 for (ip in download) {
50 total_bytes[ip] = download[ip] + upload[ip]
51 }
52
53 # Sort IPs by total bytes in descending order
54 n = asorti(total_bytes, sorted_ips, "@val_num_desc")
55
56 for (i = 1; i <= n; i++) {
57 ip = sorted_ips[i]
58 download_data = download[ip] > 0 ? download[ip] : 0
59 upload_data = upload[ip] > 0 ? upload[ip] : 0
60 printf "%-15s\t%-15d\t%-15d\n", ip, download_data, upload_data
61 }
62 }' $TMP_FILE
63
64 # Print separator line
65 echo "======================================="
66
67 # Clean up the temporary file
68 rm -f $TMP_FILE
69 done
70}
71
72# Call function with passed argument (network interface)
73monitor_traffic $1
74
install.sh Raw
1sudo wget https://gist.aiursoft.cn/anduin/e66120d03c9945dda921d0fb2039cb38/raw/HEAD/MoniTraffic.sh -O /usr/local/bin/moninet