#!/bin/bash
WEBHOOK_URL=
"https://oapi.dingtalk.com/robot/send?access_token=your_access_token"
LOG_FILE=
"/var/log/auth.log"
PATTERN=
"Failed password"
THRESHOLD=5
CURRENT_TIME=$(
date
"+%Y-%m-%d %H:%M:%S"
)
IP_ATTEMPTS=$(
grep
"$PATTERN"
$LOG_FILE |
grep
-oP
'from \K(\S+)'
|
sort
|
uniq
-c |
sort
-nr)
LAST_ALERT_FILE=
"/tmp/last_alert_ips.txt"
if
[ -f
"$LAST_ALERT_FILE"
];
then
LAST_ALERT_IPS=$(
cat
"$LAST_ALERT_FILE"
)
else
LAST_ALERT_IPS=
""
fi
ALERT_IPS=
""
NEW_ALERT_IPS=
""
BLACKLIST_IPS=
""
while
read
-r count ip;
do
if
[
"$count"
-gt
"$THRESHOLD"
];
then
if
[[ !
"$LAST_ALERT_IPS"
=~
"$ip"
]];
then
NEW_ALERT_IPS=
"$NEW_ALERT_IPS\n*IP 地址* [**$ip**] 尝试登录次数:$count 次"
BLACKLIST_IPS=
"$BLACKLIST_IPS\n$ip"
iptables -A INPUT -s
"$ip"
-j DROP
echo
"IP 地址 $ip 已被添加到黑名单并封禁。"
fi
fi
done
<<<
"$IP_ATTEMPTS"
if
[ -n
"$NEW_ALERT_IPS"
];
then
MESSAGE=
"警告:检测到以下 IP 地址的 SSH 异常登录尝试。\n当前时间:$CURRENT_TIME\n$NEW_ALERT_IPS"
curl -X POST $WEBHOOK_URL \
-H
"Content-Type: application/json"
\
-d '{
"msgtype"
:
"text"
,
"text"
: {
"content"
:
"'"
$MESSAGE
"'"
}
}'
echo
-e
"$LAST_ALERT_IPS\n$NEW_ALERT_IPS"
|
grep
-oP
'from \K(\S+)'
|
sort
|
uniq
>
"$LAST_ALERT_FILE"
fi
if
[ -n
"$BLACKLIST_IPS"
];
then
echo
-e
"以下 IP 地址已被添加到黑名单并封禁:$BLACKLIST_IPS"
>>
/var/log/ssh_blacklist
.log
fi