SMB_Filter/filter.sh

40 lines
1.1 KiB
Bash

#!/bin/bash
CPU_THRESHOLD=90.0
TIME_THRESHOLD=$((10 * 3600)) #10 hours in seconds
# Getting all Process IDs running on Port 445 or 139 (Default SMB ports)
SMB_PIDS=$(ss -tanp '( sport = :445 or sport = :139 )' 2>/dev/null \
| awk -F ',' 'NR>1 && $2 ~ /pid=/ {
split($2,a," ");
split(a[1],b,"=");
print b[2]
}' | sort -u)
if [ -z "$SMB_PIDS" ]; then
echo "No SMB connections found."
exit 0
fi
# Checking to see if any PIDs exceed CPU or Time thresholds
ps -eo pid,comm,%cpu,etimes --no-headers | awk -v cpu="$CPU_THRESHOLD" -v time="$TIME_THRESHOLD" -v smb_pids="$SMB_PIDS" '
BEGIN {
split(smb_pids, arr, " ")
for (i in arr) {
smb[arr[i]] = 1
}
}
NR > 1 {
if(!($1 in smb)) {
next
}
elapsed = $4
# Comparing elapsed to thresholds
if ($3 >= cpu && elapsed >= time) {
printf "PID: %s | Command: %s | CPU: %s%% | Runtime: %s (%.2f hours)\n",$1, $2, $3, $4, elapsed/3600
}
}'