买的tx云服务器,每天登录上去就提示成千上万条尝试登录记录,看着就烦。于是找到个禁止ip登录的方法。
/etc/hosts.allow和/etc/hosts.deny,这两个文件中添加ip可以允许和禁止指定ip登录。不过由于我登录的ip是动态的,只能使用deny文件去禁止其他ip登录。如果自己登录的IP是固定的,可以直接在deny中配置sshd:all
,再在allow中配置sshd:你的IP
,这样就只有你自己能登录了,不用再担心别人恶意爆破了。
配置如下
$ cat /etc/hosts.deny |head -n 20
#
# hosts.deny This file contains access rules which are used to
# deny connections to network services that either use
# the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# The rules in this file can also be set up in
# /etc/hosts.allow with a 'deny' option instead.
#
# See 'man 5 hosts_options' and 'man 5 hosts_access'
# for information on rule syntax.
# See 'man tcpd' for information on tcp_wrappers
#
sshd:209.141.35.3
sshd:45.61.188.131
sshd:137.184.7.179
sshd:178.62.3.183
sshd:91.215.137.38
默认修改就生效了的,不用重启什么的操作。/etc/hosts.allow不配置就是允许所有IP。若配置了会先读取allow文件,没有匹配再读取deny文件。
写了个脚本,对尝试登录10次失败的IP加入到deny文件中:
#!/bin/sh
#登录失败次数大于10的ip
IP=$(awk '/Failed/{print $(NF-3)}' /var/log/secure | sort |uniq -c |awk '{if($1>10) print $2}')
hostdeny=/etc/hosts.deny
for i in $IP
do
#如果ip不存在,则写入deny文件
if [ ! $(grep $i $hostdeny) ];then
echo "sshd:$i" >> $hostdeny
fi
done
登录失败的操作记录可以在/var/log/secure
日志文件中查看,也可以使用lastb
命令查看。
$ lastb |head
testing ssh:notty 47.103.112.43 Wed Feb 16 11:23 - 11:23 (00:00)
jp ssh:notty 177.74.124.97 Wed Feb 16 11:23 - 11:23 (00:00)
mi ssh:notty 1.117.157.44 Wed Feb 16 11:23 - 11:23 (00:00)
jp ssh:notty 177.74.124.97 Wed Feb 16 11:23 - 11:23 (00:00)
root ssh:notty 109.237.110.198 Wed Feb 16 11:23 - 11:23 (00:00)
mi ssh:notty 1.117.157.44 Wed Feb 16 11:23 - 11:23 (00:00)
summit ssh:notty 43.156.42.20 Wed Feb 16 11:23 - 11:23 (00:00)
root ssh:notty 42.194.142.143 Wed Feb 16 11:23 - 11:23 (00:00)
summit ssh:notty 43.156.42.20 Wed Feb 16 11:23 - 11:23 (00:00)
paco ssh:notty 181.61.221.93 Wed Feb 16 11:23 - 11:23 (00:00)