ssh_bruteforce 자동차단
#!/bin/bash
#횟수설정
sshban="15"
##################################
declare -a ssh_deny_ip_array
search_today=`date +'%b %e'`
today=`date +%Y%m`
time=`date +'%Y:%m:%d %H:%M:%S'`
log="/usr/local/logs/ssh_ban_$today"
_check() {
if [ ! -d /usr/local/logs ]; then
mkdir -p /usr/local/logs
fi
if [ ! -f /etc/hosts.deny ]; then
touch /etc/hosts.deny
fi
if [ ! -f $log ]; then
touch $log
fi
}
_log() {
log_ip_cnt=${#ssh_deny_ip_array[@]}
echo "[ ${time} ]" >> $log
echo "" >> $log
for ((i=0;i<=$log_ip_cnt;i++)); do
echo ${ssh_deny_ip_array[$i]} >> $log
done
echo "" >> $log
}
_common() {
declare -a ssh_ip_ban_list_array
#오늘날짜 검색이후 IP추출 및 비교후 데이터저장
IFS=$'\n' ssh_ip_count_list=(`cat /var/log/secure | grep 'Failed password for' | egrep -v 'invalid user' | grep ${search_today} | awk '{print $11}' | sort -rn -k 11 | uniq -c | awk '{print $1}'`)
k="0"
j="1"
for value in "${ssh_ip_count_list[@]}"; do
if [ $value -ge $sshban ]; then
ssh_ip_list=`cat /var/log/secure | grep 'Failed password for' | egrep -v 'invalid user' | grep ${search_today} | awk '{print $11}' | sort -rn -k 11 | uniq -c | awk '{print $2}' | sed -n "${j},${j}p"`
ssh_ip_ban_list_array[$k]=`echo $ssh_ip_list`
k=`expr $k + 1`
fi
j=`expr $j + 1`
done
#기존 리스트 비교 후 삽입
declare -a ssh_deny_ip
u=0;
ssh_ip_ban_cnt=${#ssh_ip_ban_list_array[@]}
for ((i=0;i<$ssh_ip_ban_cnt;i++)); do
ssh_deny_ip_switch="n"
while read line; do
if [[ `echo $line | grep ^S` ]] || [[ `echo $line | grep ^s` ]]; then
ssh_deny_ip=`echo $line | awk '{print $3}'`
if [[ "${ssh_ip_ban_list_array[$i]}" == "$ssh_deny_ip" ]]; then
ssh_deny_ip_switch="y"
break
fi
fi
done < /etc/hosts.deny
if [[ $ssh_deny_ip_switch == "n" ]]; then
echo "sshd : ${ssh_ip_ban_list_array[$i]}" >> /etc/hosts.deny
ssh_deny_ip_array[$u]=${ssh_ip_ban_list_array[$i]}
u=`expr $u + 1`
fi
done
if [ ! -z `echo ${ssh_deny_ip_array[@]}` ]; then
_log
fi
}
_check
_common
'리눅스 > 스크립트' 카테고리의 다른 글
실시간 트래픽 체크 (0) | 2017.02.02 |
---|---|
system 정보보기 스크립트 (0) | 2017.01.31 |
웹 트래픽 로그 순위 추출 (0) | 2016.11.03 |
apache 자동다운받기 (0) | 2016.03.04 |
mysql replication 상태체크 (0) | 2016.01.13 |