centos7 安装denyhosts,登录ssh失败后禁用ip讲解

导读:今天发现服务器centos7的日志/var/log/secure,有一些不是自己登陆的服务器ip登录失败。对服务器造成了攻击。
解决的办法,有三种方式解决。分别是自定义的shell程序,denyhosts命令和fail2ban
第一种方法:
第一步
在/usr/local/bin/文件下创建文件ssh_secure.sh
编辑文件: 
[root@123www log]# vi  /usr/local/bin/ssh_secure.sh 写入下列内容。
[root@123www log]# cat  /usr/local/bin/ssh_secure.sh
#! /bin/bash
#表示的经过处理打印输出到新的日志里
cat /var/log/secure|awk ‘/Failed password/{print $(NF-3)}’|sort|uniq -c|awk ‘{print $2″=”$1;}’ > /var/log/log123.log
#在新的日志文件在进行判断
for i in cat  /var/log/log123.log
do
IP=echo $i |awk -F= '{print $1}'
NUM=echo $i|awk -F= '{print $2}'
#如果是ip数量失败大于3了就锁定ip写入系统host.deny文件中
        if [ ${NUM} -gt 3 ]; then
                grep $IP /etc/hosts.deny > /dev/null
                if [ $? -gt 0 ];then
                      echo “sshd:$IP:deny” >> /etc/hosts.deny  (注:#加入不允许登录的地方写入hosts.deny  也可以加入防火墙呢。)
                fi
        fi
done
[root@123www log]#
第二步:加入计划任务里面
   查看计划任务:crontab -l
   编辑计划任务 :crontab -e
*/1 * * * * sh /usr/local/bin/secure_ssh.sh
第二种方法:
    安装denyhosts命令
    centos7 通过yum安装 yum install -y denyhosts
    配置文件路径
    vi /etc/denyhosts.conf
在配置前,清空/var/log/secure 文件内容
以防自己屏蔽了。
systemctl start   denyhosts   开启denyhosts
systemctl enable  denyhosts   开机启动
systemctl restart denyhosts   重启
接下里就配置denyhosts文件了,请仔细阅读
       ############ THESE SETTINGS ARE REQUIRED ############
########################################################################
#
# SECURE_LOG: the log file that contains sshd logging info
# if you are not sure, grep “sshd:” /var/log/*
#
# The file to process can be overridden with the –file command line
# argument
#
# Redhat or Fedora Core: 自己的日志文件这里指的是redhat,fedora 和centos7
SECURE_LOG = /var/log/secure
#
# Mandrake, FreeBSD or OpenBSD:
#SECURE_LOG = /var/log/auth.log
#
# SuSE:
#SECURE_LOG = /var/log/messages
#
# Mac OS X (v10.4 or greater –
#   also refer to:   http://www.denyhost.net/faq.html#macos
#SECURE_LOG = /private/var/log/asl.log
#
# Mac OS X (v10.3 or earlier):
#SECURE_LOG=/private/var/log/system.log
#
# Debian and Ubuntu
#SECURE_LOG = /var/log/auth.log
########################################################################
########################################################################
#
# HOSTS_DENY: the file which contains restricted host access information
#
# Most operating systems:开启了阻止的ip文件
HOSTS_DENY = /etc/hosts.deny
#
# Some BSD (FreeBSD) Unixes:
#HOSTS_DENY = /etc/hosts.allow
#
# Another possibility (also see the next option):
#HOSTS_DENY = /etc/hosts.evil
#######################################################################
########################################################################
#
# PURGE_DENY: removed HOSTS_DENY entries that are older than this time
#             when DenyHosts is invoked with the –purge flag
#
#      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 =
#
# purge entries older than 1 week
#PURGE_DENY = 1w
#
# purge entries older than 5 days
#PURGE_DENY = 5d
#
# For the default Fedora install, we want timestamping but no
# expiration (at least by default) so this is deliberately set high.
# Adjust to taste.
#多久清除屏蔽的IP的记录。
#过多久后清除已经禁止的,其中w代表周,d代表天,h代表小时,s代表秒,m代表分钟
PURGE_DENY = 5m
#######################################################################
#######################################################################
#
# PURGE_THRESHOLD: defines the maximum times a host will be purged.
# Once this value has been exceeded then this host will not be purged.
# Setting this parameter to 0 (the default) disables this feature.
#定义某个host最多被清除几次。 超过PURGE_THRESHOLD值就不会被清理了。
# default: a denied host can be purged/re-added indefinitely
#PURGE_THRESHOLD = 0
#
# a denied host will be purged at most 2 times.
#PURGE_THRESHOLD = 2
#
#######################################################################
#######################################################################
#
# BLOCK_SERVICE: the service name that should be blocked in HOSTS_DENY
#
# man 5 hosts_access for details
#
# eg.   sshd: 127.0.0.1  # will block sshd logins from 127.0.0.1
#表示阻止的服务名。默认为sshd,也可以设置FTP、SMPT等。也可以设置ALL所有的服务都禁止
# To block all services for the offending host:
#BLOCK_SERVICE = ALL
# To block only sshd:
BLOCK_SERVICE  = sshd
# To only record the offending host and nothing else (if using
# an auxilary file to list the hosts).  Refer to:
#BLOCK_SERVICE =
#
#######################################################################
#######################################################################
#
# DENY_THRESHOLD_INVALID: block each host after the number of failed login
# attempts has exceeded this value.  This value applies to invalid
# user login attempts (eg. non-existent user accounts)
#允许无效用户失败的次数
DENY_THRESHOLD_INVALID = 5
#
#######################################################################
#######################################################################
#
# DENY_THRESHOLD_VALID: block each host after the number of failed
# login attempts has exceeded this value.  This value applies to valid
# user login attempts (eg. user accounts that exist in /etc/passwd) except
# for the “root” user
#允许有效用户失败的次数
DENY_THRESHOLD_VALID = 10
#
#######################################################################
#######################################################################
#
# DENY_THRESHOLD_ROOT: block each host after the number of failed
# login attempts has exceeded this value.  This value applies to
# “root” user login attempts only.
#允许root用户失败的次数
DENY_THRESHOLD_ROOT = 1
#
#######################################################################
#######################################################################
#
# DENY_THRESHOLD_RESTRICTED: block each host after the number of failed
# login attempts has exceeded this value.  This value applies to
# usernames that appear in the WORK_DIR/restricted-usernames file only.
#允许写入数据到  /var/lib/denyhosts
DENY_THRESHOLD_RESTRICTED = 1
#
#######################################################################
#######################################################################
#
# WORK_DIR: the path that DenyHosts will use for writing data to
# (it will be created if it does not already exist).
#
# Note: it is recommended that you use an absolute pathname
# for this value (eg. /home/foo/denyhost/data)
#
WORK_DIR = /var/lib/denyhosts
#
#######################################################################
#######################################################################
#
# ETC_DIR: the path that DenyHosts will use for reading data when
# we need configuration information.
#
# Note: it is recommended that you use an absolute pathname
# for this value (eg. /etc or /usr/local/etc)
#
ETC_DIR = /etc
#
#######################################################################
#######################################################################
#
# SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS
#
# SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES|NO
# If set to YES, if a suspicious login attempt results from an allowed-host
# then it is considered suspicious.  If this is NO, then suspicious logins
# from allowed-hosts will not be reported.  All suspicious logins from
# ip addresses that are not in allowed-hosts will always be reported.
#
#SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES
######################################################################
######################################################################
#
# HOSTNAME_LOOKUP
#
# HOSTNAME_LOOKUP=YES|NO
# If set to YES, for each IP address that is reported by Denyhosts,
# the corresponding hostname will be looked up and reported as well
# (if available).
#反向解析,默认是yes
#HOSTNAME_LOOKUP=NO
#
######################################################################
######################################################################
#
# LOCK_FILE
#
# LOCK_FILE=/path/denyhosts
# If this file exists when DenyHosts is run, then DenyHosts will exit
# immediately.  Otherwise, this file will be created upon invocation
# and deleted upon exit.  This ensures that only one instance is
# running at a time.
#
# Redhat/Fedora:
LOCK_FILE = /var/lock/subsys/denyhosts
#
# Debian
#LOCK_FILE = /var/run/denyhosts.pid
#
# Misc
#LOCK_FILE = /tmp/denyhosts.lock
#
######################################################################
       ############ THESE SETTINGS ARE OPTIONAL ############
#######################################################################
#
# IPTABLES: if you would like DenyHost to block incoming connections
# using the Linux firewall IPTABLES, then set the following variable
# to the path of the iptables executable. Typically this is
# /sbin/iptables
# If this option is not set or commented out then the iptables
# firewall is not used.
#IPTABLES = /sbin/iptables
#
# Warning: If you are running IPTABLES, please make sure to comment
# out the PFCTL_PATH and the PF_TABLE variables below. PF and
# IPTABLES should not be running together on the same operating system.
#
# By default DenyHost will ask IPTables to block incoming connections
# from an aggressive host on ALL ports. While this is usually a good
# idea, it may prevent some botted machines from being able to access
# services their legitmate users want, like a web server. To only
# block specific ports, enable the following option.
# BLOCKPORT = 22
#
#######################################################################
#######################################################################
#
# On FreeBSD/OpenBSD/TrueOS/PC-BSD/NetBSD we may want to block incoming
# traffic using the PF firewall instead of the hosts.deny file
# (aka tcp_wrapper).
# The admin can set up a PF table that is persistent
# and DenyHost can add new addresses to be blocked to that table.
# The TrueOS operating system enables this by default, blocking
# all addresses in the “blacklist” table.
#
# To have DenyHost update the blocking PF table in real time, uncomment
# these next two options. Make sure the table name specificed
# is one created in the pf.conf file of your operating system.
# The PFCTL_PATH variable must point to the pfctl extectuable on your OS.
# PFCTL_PATH = /sbin/pfctl
# PF_TABLE = blacklist
# Note, a good rule to have in your pf.conf file to enable the
# blacklist table is:
#
# table <blacklist> persist file “/etc/blacklist”
# block from <blacklist> to any
#
# Warning: If you are using PF, please make sure to disable the
# IPTABLES rule above as these two packet filters should not be
# run together on the same operating system.
# Note: Even if you decide to run DenyHost with PF filtering
# only and no hosts.deny support, please still create an empty
# file called /etc/hosts.deny for backward compatibility.
# Also, please make sure PF is enabled prior to launching
# DenyHosts. To do this run “pfctl -e”.
#######################################################################
#######################################################################
#
# ADMIN_EMAIL: if you would like to receive emails regarding newly
# restricted hosts and suspicious logins, set this address to
# match your email address.  If you do not want to receive these reports
# leave this field blank (or run with the –noemail option)
#
# Multiple email addresses can be delimited by a comma, eg:
#
ADMIN_EMAIL = sudo-lianxi@139.com
#
#######################################################################
#######################################################################
#
# SMTP_HOST and SMTP_PORT: if DenyHosts is configured to email
# reports (see ADMIN_EMAIL) then these settings specify the
# email server address (SMTP_HOST) and the server port (SMTP_PORT)
#
#建议用25端口的服务器,denyhosts暂时不能用ssl
SMTP_HOST = smtp.139.com
SMTP_PORT = 25
#
#######################################################################
#######################################################################
#
# SMTP_USERNAME and SMTP_PASSWORD: set these parameters if your
# smtp email server requires authentication
#
SMTP_USERNAME=sudotest@139.com
SMTP_PASSWORD=admin@123456789
#
######################################################################
#######################################################################
#
# SMTP_FROM: you can specify the “From:” address in messages sent
# from DenyHosts when it reports thwarted abuse attempts
#
#SMTP_FROM = DenyHosts <nobody@localhost>
SMTP_FROM = DenyHosts <sudotest@139.com>
#
#######################################################################
#######################################################################
#
# SMTP_SUBJECT: you can specify the “Subject:” of messages sent
# by DenyHosts when it reports thwarted abuse attempts
SMTP_SUBJECT = DenyHosts Report from $[HOSTNAME]
#
######################################################################
######################################################################
#
# SMTP_DATE_FORMAT: specifies the format used for the “Date:” header
# when sending email messages.
#
# for possible values for this parameter refer to: man strftime
#
# the default:
#
#SMTP_DATE_FORMAT = %a, %d %b %Y %H:%M:%S %z
#
######################################################################
######################################################################
#
# SYSLOG_REPORT
#
# SYSLOG_REPORT=YES|NO
# If set to yes, when denied hosts are recorded the report data
# will be sent to syslog (syslog must be present on your system).
# The default is: NO
#
#SYSLOG_REPORT=NO
#
#SYSLOG_REPORT=YES
#
######################################################################
######################################################################
#
# ALLOWED_HOSTS_HOSTNAME_LOOKUP
#
# ALLOWED_HOSTS_HOSTNAME_LOOKUP=YES|NO
# If set to YES, for each entry in the WORK_DIR/allowed-hosts file,
# the hostname will be looked up.  If your versions of tcp_wrappers
# and sshd sometimes log hostnames in addition to ip addresses
# then you may wish to specify this option.
# #启用allow-hosts 白名单文件功能  如果/var/lib/denyhosts没有allowed-hosts文件就手动创建下把自己的ip和允许的ip加入里面即可多ip要换行
#ALLOWED_HOSTS_HOSTNAME_LOOKUP=NO
ALLOWED_HOSTS_HOSTNAME_LOOKUP=YES
#
######################################################################
######################################################################
#
# AGE_RESET_VALID: Specifies the period of time between failed login
# attempts that, when exceeded will result in the failed count for
# this host to be reset to 0.  This value applies to login attempts
# to all valid users (those within /etc/passwd) with the
# exception of root.  If not defined, this count will never
# be reset.
#
# See the comments in the PURGE_DENY section (above)
# for details on specifying this value or for complete details
#有效用户登录失败计数归零的时间
#AGE_RESET_VALID=5d
AGE_RESET_VALID=5d
#
######################################################################
######################################################################
#
# AGE_RESET_ROOT: Specifies the period of time between failed login
# attempts that, when exceeded will result in the failed count for
# this host to be reset to 0.  This value applies to all login
# attempts to the “root” user account.  If not defined,
# this count will never be reset.
#
# See the comments in the PURGE_DENY section (above)
# for details on specifying this value or for complete details
#root用户登录失败计数归零的时间
AGE_RESET_ROOT=25d
#
######################################################################
######################################################################
#
# AGE_RESET_RESTRICTED: Specifies the period of time between failed login
# attempts that, when exceeded will result in the failed count for
# this host to be reset to 0.  This value applies to all login
# attempts to entries found in the WORK_DIR/restricted-usernames file.
# If not defined, the count will never be reset.
#
# See the comments in the PURGE_DENY section (above)
# for details on specifying this value or for complete details
#用户的失败登录计数重置为0的时间(/usr/share/denyhosts/data/restricted-usernames)
AGE_RESET_RESTRICTED=25d
#
######################################################################
######################################################################
#
# AGE_RESET_INVALID: Specifies the period of time between failed login
# attempts that, when exceeded will result in the failed count for
# this host to be reset to 0.  This value applies to login attempts
# made to any invalid username (those that do not appear
# in /etc/passwd).  If not defined, count will never be reset.
#
# See the comments in the PURGE_DENY section (above)
# for details on specifying this value or for complete details
#无效用户登录失败计数归零的时间
AGE_RESET_INVALID=10d
#
######################################################################
######################################################################
#
# RESET_ON_SUCCESS: If this parameter is set to “yes” then the
# failed count for the respective ip address will be reset to 0
# if the login is successful.
#
# The default is RESET_ON_SUCCESS = no
#
#RESET_ON_SUCCESS = yes
#
#####################################################################
######################################################################
#
# PLUGIN_DENY: If set, this value should point to an executable
# program that will be invoked when a host is added to the
# HOSTS_DENY file.  This executable will be passed the host
# that will be added as its only argument.
#
#PLUGIN_DENY=/usr/bin/true
#
######################################################################
######################################################################
#
# PLUGIN_PURGE: If set, this value should point to an executable
# program that will be invoked when a host is removed from the
# HOSTS_DENY file.  This executable will be passed the host
# that is to be purged as it’s only argument.
#
#PLUGIN_PURGE=/usr/bin/true
#
# The following plugin will restore the file contexts on /etc/hosts.deny after
# denyhosts purges old entries.  This prevents breakage when selinux is set to
# enforcing mode, but still has a small window where the context is set
# incorrectly.  The correct place to fix this is in the selinux policy.
#
#PLUGIN_PURGE=/usr/share/denyhosts/plugins/restorecon.sh
#
######################################################################
######################################################################
#
# USERDEF_FAILED_ENTRY_REGEX: if set, this value should contain
# a regular expression that can be used to identify additional
# hackers for your particular ssh configuration.  This functionality
# extends the built-in regular expressions that DenyHosts uses.
# This parameter can be specified multiple times.
# See this faq entry for more details:
#
#USERDEF_FAILED_ENTRY_REGEX=
#
#
######################################################################
   ######### THESE SETTINGS ARE SPECIFIC TO DAEMON MODE  ##########
#######################################################################
#
# DAEMON_LOG: when DenyHosts is run in daemon mode (–daemon flag)
# this is the logfile that DenyHosts uses to report its status.
# To disable logging, leave blank.  (default is: /var/log/denyhosts)
#
DAEMON_LOG = /var/log/denyhosts
#
# disable logging:
#DAEMON_LOG =
#
######################################################################
#######################################################################
#
# DAEMON_LOG_TIME_FORMAT: when DenyHosts is run in daemon mode
# (–daemon flag) this specifies the timestamp format of
# the DAEMON_LOG messages (default is the ISO8061 format:
# ie. 2005-07-22 10:38:01,745)
#
# for possible values for this parameter refer to: man strftime
#
# Jan 1 13:05:59
#DAEMON_LOG_TIME_FORMAT = %b %d %H:%M:%S
#
# Jan 1 01:05:59
#DAEMON_LOG_TIME_FORMAT = %b %d %I:%M:%S
#
######################################################################
#######################################################################
#
# DAEMON_LOG_MESSAGE_FORMAT: when DenyHosts is run in daemon mode
# (–daemon flag) this specifies the message format of each logged
# entry.  By default the following format is used:
#
# %(asctime)s – %(name)-12s: %(levelname)-8s %(message)s
#
# Where the “%(asctime)s” portion is expanded to the format
# defined by DAEMON_LOG_TIME_FORMAT
#
# This string is passed to python’s logging.Formatter contstuctor.
# For details on the possible format types please refer to:
#
# This is the default:
#DAEMON_LOG_MESSAGE_FORMAT = %(asctime)s – %(name)-12s: %(levelname)-8s %(message)s
#
#
######################################################################
#######################################################################
#
# DAEMON_SLEEP: when DenyHosts is run in daemon mode (–daemon flag)
# this is the amount of time DenyHosts will sleep between polling
# the SECURE_LOG.  See the comments in the PURGE_DENY section (above)
# for details on specifying this value or for complete details
#
#每隔30s搜索一下日志
DAEMON_SLEEP = 30s
#
#######################################################################
#######################################################################
#表示DenyHosts在守护进程模式下运行的频率,运行清除机制清除HOSTS_DENY中的过期的记录
#如果PURGE_DENY为空,这没有任何效果。
# DAEMON_PURGE: How often should DenyHosts, when run in daemon mode,
# run the purge mechanism to expire old entries in HOSTS_DENY
# This has no effect if PURGE_DENY is blank.
#
#DAEMON_PURGE = 1h
DAEMON_PURGE = 10m
#
#######################################################################
   #########   THESE SETTINGS ARE SPECIFIC TO     ##########
   #########       DAEMON SYNCHRONIZATION         ##########
#######################################################################
#
# Synchronization mode allows the DenyHosts daemon the ability
# to periodically send and receive denied host data such that
# DenyHosts daemons worldwide can automatically inform one
# another regarding banned hosts.   This mode is disabled by
# default, you must uncomment SYNC_SERVER to enable this mode.
#
# for more information, please refer to:
#        http:/denyhost.sourceforge.net/faq.html
#
#######################################################################
#######################################################################
#
# SYNC_SERVER: The central server that communicates with DenyHost
# daemons.
#
# To disable synchronization (the default), do nothing.
#
# To enable synchronization, you must uncomment the following line:
#
# NOTE: Please read README.Fedora before enabling sync
#
#######################################################################
#######################################################################
#
# SYNC_INTERVAL: the interval of time to perform synchronizations if
# SYNC_SERVER has been uncommented.  The default is 1 hour.
#
#SYNC_INTERVAL = 1h
#
#######################################################################
#######################################################################
#
# SYNC_UPLOAD: allow your DenyHosts daemon to transmit hosts that have
# been denied?  This option only applies if SYNC_SERVER has
# been uncommented.
# The default is SYNC_UPLOAD = yes
#
SYNC_UPLOAD = no
#SYNC_UPLOAD = yes
#
#######################################################################
#######################################################################
#
# SYNC_DOWNLOAD: allow your DenyHosts daemon to receive hosts that have
# been denied by others?  This option only applies if SYNC_SERVER has
# been uncommented.
# The default is SYNC_DOWNLOAD = yes
#
SYNC_DOWNLOAD = no
#SYNC_DOWNLOAD = yes
#
#
#
#######################################################################
#######################################################################
#
# SYNC_DOWNLOAD_THRESHOLD: If SYNC_DOWNLOAD is enabled this parameter
# filters the returned hosts to those that have been blocked this many
# times by others.  That is, if set to 1, then if a single DenyHosts
# server has denied an ip address then you will receive the denied host.
#
# See also SYNC_DOWNLOAD_RESILIENCY
#
#SYNC_DOWNLOAD_THRESHOLD = 10
#
# The default is SYNC_DOWNLOAD_THRESHOLD = 3
#
#SYNC_DOWNLOAD_THRESHOLD = 3
#
#######################################################################
#######################################################################
#
# SYNC_DOWNLOAD_RESILIENCY:  If SYNC_DOWNLOAD is enabled then the
# value specified for this option limits the downloaded data
# to this resiliency period or greater.
#
# Resiliency is defined as the timespan between a hackers first known
# attack and its most recent attack.  Example:
#
# If the centralized  denyhosts.net server records an attack at 2 PM
# and then again at 5 PM, specifying a SYNC_DOWNLOAD_RESILIENCY = 4h
# will not download this ip address.
#
# However, if the attacker is recorded again at 6:15 PM then the
# ip address will be downloaded by your DenyHosts instance.
#
# This value is used in conjunction with the SYNC_DOWNLOAD_THRESHOLD
# and only hosts that satisfy both values will be downloaded.
# This value has no effect if SYNC_DOWNLOAD_THRESHOLD = 1
#
# The default is SYNC_DOWNLOAD_RESILIENCY = 5h (5 hours)
#
# Only obtain hackers that have been at it for 2 days or more:
#SYNC_DOWNLOAD_RESILIENCY = 2d
#
# Only obtain hackers that have been at it for 5 hours or more:
#SYNC_DOWNLOAD_RESILIENCY = 5h
#
#######################################################################
最后:别忘记了重启denyhosts服务
systemctl restart denyhosts 即可可以通过测试
用其他的ip客服端登录测试:ssh -l test  你的服务器ip地址 -p 22
最后查看:
cat /etc/host.deny就显示禁止的ip了。
第三种方法:
使用Fail2Ban软件,fail2ban 是一款入侵防御软件,可以保护服务器免受暴力攻击。如需详情请去baidu搜索下。以上两种比较简单。我用的第二种方法。

如果有不懂的地方请留言,SKY8G网站编辑者专注于研究IT源代码研究与开发。希望你下次光临,你的认可和留言是对我们最大的支持,谢谢!

上一篇: magento1.x清理缓存命令

下一篇: 如何在CentOS 7上添加swap分区

登录 评论
avatar