Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 用戶登出自動重設 hosts.allow/deny 限制 IP 登入 Shell 腳本實作

編輯:關於 Linux

生產環境中,其他管理員可能修改 hosts.allow 放行更多 IP。為統一管理,可在用戶登出時自動重置存取控制檔案,並自動允許本機配置的 IP 段登入。

核心腳本 (.bash_logout)

test -f /root/.bash_logout && chattr -i /root/.bash_logout
cat > /root/.bash_logout << 'EOF'
export TERM=xterm
/usr/bin/chattr -i /etc/hosts.allow /etc/hosts.deny

# 產生 hosts.deny:拒絕所有,除本機網段
/bin/awk 'BEGIN{FS="[=.]";RS="\n"};/^IPADDR/{print "sshd:all EXCEPT "$2"."$3"."$4".0/255.255.255.0"}' /etc/sysconfig/network-scripts/ifcfg-* | grep -v 127.0.0 | uniq > /etc/hosts.deny
/bin/cat >> /etc/hosts.deny << 'iEOF'
sshd:all EXCEPT ip
iEOF

# 產生 hosts.allow:允許本機網段
/bin/awk 'BEGIN{FS="[=.]";RS="\n"};/^IPADDR/{print "sshd:"$2"."$3"."$4".0/255.255.255.0"}' /etc/sysconfig/network-scripts/ifcfg-* | grep -v 127.0.0 | uniq > /etc/hosts.allow
/bin/cat >> /etc/hosts.allow << 'iEOF'
sshd:ip (www.111cn.net)
iEOF

/usr/bin/chattr +i /etc/hosts.allow /etc/hosts.deny
clear
EOF

sh /root/.bash_logout 2>&1 >/dev/null

異常 IP 登入郵件告警腳本

#!/bin/bash
# 檢測惡意 IP 登入並郵件報警(可搭配 139 郵箱實現簡訊通知)
Ldate=`which date`; Lawk=`which awk`; Llast=`which last`
Lgrep=`which grep`; Lsendmail=`which sendmail`; Lifconfig=`which ifconfig`
serverip=`$Lifconfig eth0|$Lgrep inet|$Lawk -F: '{print $2}'|$Lawk '{print $1}'`
cutdate=`$Ldate |$Lawk '{print $1" "$2" "$3}'`
hackerip=`$Llast|$Lgrep "$cutdate"|$Lawk '{print $3}'|$Lgrep -v 192.168.1x.xx`
if [ -z "$hackerip" ]; then exit; fi
for logip in $hackerip; do
  echo "hacker ip is $logip already login $serverip" | mail -s "SOS" rocdk890@139.com
done

此腳本可排程執行,發現非預期 IP 登入即發送告警。

Copyright © Windows教程網 All Rights Reserved