-
Notifications
You must be signed in to change notification settings - Fork 3
/
antissh.sh
46 lines (41 loc) · 1.21 KB
/
antissh.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env bash
# @Author: Seaky
# @Date: 2022/1/28 16:20
HEAD_COUNT=50
FAIL_COUNT=10
WHITELIST=''
LOG_GEO=true
DEBUG=false
for cmd in "curl" "jq"; do
if [ -z "`which $cmd`" ] ; then
echo "Install $cmd first"
exit 1
fi
done
prelist=`cat /etc/hosts.deny | egrep -v '^\s*$' | egrep -v '^#' | cut -d":" -f 2 | xargs`
succ_ips=`last | head -n $HEAD_COUNT | awk '/^[^ ]+.*pts/{print $3}' | sort | uniq | xargs`
fail_ips=`lastb | head -n $HEAD_COUNT | awk '/^[^ ]+.*ssh:notty/{print $3}' |
sort | uniq -c | sort -r |
awk -v th=$FAIL_COUNT '{if($1>th){print $2}}' | xargs`
for ip in $fail_ips
do
if [[ " ${WHITELIST[*]} " =~ " ${ip} " ]] ; then
$DEBUG && echo "$ip in whitelist"
continue
fi
if [[ " ${succ_ips[*]} " =~ " ${ip} " ]] ; then
$DEBUG && echo "$ip has login successfully before"
continue
fi
if [[ ! " ${prelist[*]} " =~ " ${ip} " ]] ; then
if $LOG_GEO ; then
a=`curl --silent https://api.ip.sb/geoip/$ip`
geo="| "`echo $a | jq .country`.`echo $a | jq .region`.`echo $a | jq .city`
fi
cmd="echo -e \"ALL:${ip}:deny # `date` ${geo//\"/}\" >> /etc/hosts.deny"
$DEBUG && echo $cmd
eval $cmd
else
$DEBUG && echo "$ip is in ban list"
fi
done