DenyHosts 简介

DenyHosts 是 Python 语言写的一个程序软件,运行于 Linux 上预防 SSH 暴力破解的,它会分析 sshd 的日志文件(/var/log/secure),当发现重复的攻击时就会记录 IP 到/etc/hosts.deny 文件,从而达到自动屏 IP 的功能。

下载DenyHosts

DenyHosts官网:http://denyhosts.sourceforge.net/

最新版本下载地址:https://sourceforge.net/projects/denyhosts/files/denyhosts/2.6/

解压并安装

  • 安装服务器系统:CentOS 7.2
# 官网下载包安装
[root@tmp ~]# tar zxvf DenyHosts-2.6.tar.gz
[root@tmp ~]# cd DenyHosts-2.6
[root@tmp ~]# DenyHosts-2.6]# python setup.py install

配置

# 进入配置目录
[root@tmp ~]# cd /usr/share/denyhosts/
# 创建配置文件
[root@tmp denyhosts]# cp denyhosts.cfg-dist denyhosts.cfg 
# 修改服务文件名称
[root@tmp denyhosts]# cp daemon-control-dist daemon-control
# 提高安全级别,修改权限
[root@tmp denyhosts]# chown root daemon-control
[root@tmp denyhosts]# chmod 700 daemon-control
[root@tmp denyhosts]# vi denyhosts.cfg
SECURE_LOG = /var/log/secure   #ssh日志文件
# format is: i[dhwmy]
# Where i is an integer (eg. 7)
# m = minutes
# h = hours
# d = days
# w = weeks
# y = years
#
# never purge:
PURGE_DENY = 50m               #过多久后清除已阻止IP
HOSTS_DENY = /etc/hosts.deny   #将阻止IP写入到hosts.deny
BLOCK_SERVICE = sshd           #阻止服务名
PURGE_THRESHOLD =              #定义了某一IP最多被解封多少次。某IP暴力破解SSH密码被阻止/解封达到了PURGE_THRESHOLD次,则会被永久禁止;
DENY_THRESHOLD_INVALID = 1     #允许无效用户登录失败的次数
DENY_THRESHOLD_VALID = 10      #允许普通用户登录失败的次数
DENY_THRESHOLD_ROOT = 5        #允许root登录失败的次数
WORK_DIR = /usr/local/share/denyhosts/data #将deny的host或ip纪录到Work_dir中
DENY_THRESHOLD_RESTRICTED = 1 #设定 deny host 写入到该资料夹
LOCK_FILE = /var/lock/subsys/denyhosts #将DenyHOts启动的pid纪录到LOCK_FILE中,已确保服务正确启动,防止同时启动多个服务。
HOSTNAME_LOOKUP=NO            #是否做域名反解
ADMIN_EMAIL =                 #设置管理员邮件地址
DAEMON_LOG = /var/log/denyhosts #DenyHosts日志位置

配置服务及启动

# 创建启动服务连接
[root@tmp ~]# ln -s /usr/share/denyhosts/daemon-control /etc/init.d/denyhosts
# 添加启动项
[root@tmp ~]# chkconfig denyhosts on
# 查看启动像是否成功
[root@tmp ~]# chkconfig --list|grep denyhosts
# 启动denyhosts
[root@tmp ~]# service denyhosts start  # 或者 systemctl start denyhosts
# 查看后台进程
[root@tmp ~]# ps -ef|grep denyhosts
root      3098  3865  0 17:35 pts/1    00:00:00 grep --color=auto denyhosts
root     21121     1  0 Feb28 ?        00:00:01 python /usr/bin/denyhosts.py --daemon --config=/usr/share/denyhosts/denyhosts.cfg

问题排查

  • starting DenyHosts: /usr/bin/env python /usr/bin/denyhosts.py –daemon –config=/usr/share/denyhosts/denyhosts.cfg python: can’t open file ‘/usr/bin/denyhosts.py’: [Errno 2] No such file or directory

解决方法:

cd /usr/share/denyhosts/
vi daemon-control
DENYHOSTS_BIN = "/usr/bin/denyhosts.py"
改为
DENYHOSTS_BIN = "/usr/local/bin/denyhosts.py"
  • ImportError: No module named DenyHosts.python_version

解决方法:

# 下面的python版本视服务器上的版本而定
cp -r /usr/local/lib/python2.7/site-packages/DenyHosts /usr/lib/python2.6/site-packages/

然后重启即可。