基于两列输出的条件判断:如何关联计数与对应IP并封禁连接
I get it, you're tracking failed access attempts (judging by your grep terms) and want to automatically target IPs that cross a certain threshold of failed tries. Here's how to tie the count to the IP and take action:
Step 1: Filter IPs with Count Above Your Threshold
First, tweak your existing pipeline to retain both the count and IP, then use awk to filter only entries where the count exceeds your specified value (let's use n=5 as an example—swap it with your actual threshold):
cat file | egrep "invalid|password" | egrep -v "Accepted|preauth" | awk '{print $13}' | sort | uniq -c | awk -v threshold=5 '$1 > threshold {print $2}'
Let’s break down the final awk piece:
-v threshold=5: Passes your threshold value intoawkas a reusable variable$1 > threshold: Checks if the first column (the failure count) is greater than your threshold{print $2}: Outputs the second column (the problematic IP) if the condition is met
Step 2: Disconnect Connections from These IPs
Once you have your list of high-failure IPs, you can loop through them to terminate active connections or block them entirely. Here are two common methods:
Method 1: Terminate Active Connections (Modern Systems)
Use ss to find connections from the IP and kill their associated processes:
cat file | egrep "invalid|password" | egrep -v "Accepted|preauth" | awk '{print $13}' | sort | uniq -c | awk -v threshold=5 '$1 > threshold {print $2}' | while read ip; do ss -tp src $ip | awk 'NR>1 {split($5, pid, ","); gsub("pid=", "", pid[2]); print pid[2]}' | xargs -r kill done
NR>1skips the header line fromss- The
split/gsublogic extracts the process ID (PID) from thessoutput -rinxargsensureskilldoesn’t run if there are no active PIDs to terminate
Method 2: Permanently Block IPs (Until Reboot)
If you want to block the IP entirely instead of just disconnecting current connections, use iptables:
cat file | egrep "invalid|password" | egrep -v "Accepted|preauth" | awk '{print $13}' | sort | uniq -c | awk -v threshold=5 '$1 > threshold {print $2}' | while read ip; do iptables -A INPUT -s $ip -j DROP done
To make this rule persist after a reboot, save your iptables config (e.g., iptables-save > /etc/iptables/rules.v4 on Debian/Ubuntu).
Bonus: Simplify Your Pipeline
You can combine the filtering steps into a single awk call to make the pipeline faster and cleaner:
awk '/invalid|password/ && !/Accepted|preauth/ {print $13}' file | sort | uniq -c | awk -v threshold=5 '$1 > threshold {print $2}'
This replaces your multiple egrep commands with one awk pass that does the same log filtering.
内容的提问来源于stack exchange,提问作者hasslefree

