萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 使用者登出後自動限制 IP 登入 Shell 腳本實戰:hosts.allow/deny 動態管理

生產環境防止其他管理員修改 hosts.allow 放寬登入限制,可在用戶登出時自動重置 hosts.allow/deny 為預設策略,並自動允許本機 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:預設拒絕所有,僅允許本機 IP 段
/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
cat >>/etc/hosts.deny <<'iEOF'
sshd:all EXCEPT ip
iEOF

# 重置 hosts.allow:僅允許本機 IP 段
/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
cat >>/etc/hosts.allow <<'iEOF'
sshd:ip
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" admin@domain.com
done

此方案實現「登出即重置、非法即告警」的動態存取控制,適合多管理員協作的生產環境。

copyright © 萬盛學電腦網 all rights reserved