Última atividade 1731231225

Revisão 9daa7c82b0974a4701f4dc56024630e008615253

MoniTraffic.sh Bruto
1#!/bin/bash
2
3function get_top_ip() {
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 (3 minutes)
13
14 # Temp file to store tcpdump output
15 TMP_FILE=$(mktemp)
16 trap "rm -f $TMP_FILE" EXIT # Ensure cleanup on exit
17
18 # Capture IPv4 traffic on the specified interface
19 echo "Capturing network traffic on $INTERFACE for $DURATION seconds..."
20 sudo timeout $DURATION tcpdump -i $INTERFACE -nn -q -tt 'ip' > $TMP_FILE
21
22 echo "Processing captured traffic data..."
23
24 # Calculate traffic statistics
25 awk '
26 /IP/ {
27 # Extract source and destination IPs using a stricter pattern to ensure only IPs are captured
28 if (match($3, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) {
29 src_ip = substr($3, RSTART, RLENGTH)
30 }
31 if (match($5, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) {
32 dst_ip = substr($5, RSTART, RLENGTH)
33 }
34
35 # Calculate packet size (bytes) - field 8 (better validation)
36 size = $NF
37 if (size ~ /^[0-9]+$/) {
38 # Count download (dst_ip) and upload (src_ip) for traffic
39 download[dst_ip] += size
40 upload[src_ip] += size
41 }
42 }
43 END {
44 print "Top 10 IPs by Traffic:"
45 printf "%-15s\t%-15s\t%-15s\n", "IP Address", "Download (bytes)", "Upload (bytes)"
46 for (ip in download) {
47 total_bytes[ip] = download[ip] + upload[ip]
48 }
49 n = asorti(total_bytes, sorted_ips, "@val_num_desc")
50 for (i = 1; i <= 10 && i <= n; i++) {
51 ip = sorted_ips[i]
52 download_data = download[ip] > 0 ? download[ip] " bytes" : "0 bytes"
53 upload_data = upload[ip] > 0 ? upload[ip] " bytes" : "0 bytes"
54 printf "%-15s\t%-15s\t%-15s\n", ip, download_data, upload_data
55 }
56 }' $TMP_FILE
57}
58
59# Call function with passed argument (network interface)
60get_top_ip $1
61