生產環境中,有可能會出現被其他管理員或使用者修改hosts.allow允許更多的ip登陸機器;為了方便統一管理,我們可以在使用者退出的時候統一修改allow和deny檔案成預設設定。同時也能自動擷取機器所配ip的整個ip段為允許登陸
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
#for 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 1>/etc/hosts.deny
/bin/cat >>/etc/hosts.deny << iEOF
sshd:all EXCEPT ip
iEOF
#for 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 1>/etc/hosts.allow
/bin/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郵箱以達到簡訊及時通知到手機的功能
#適用系統centos5
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
else
for logip in $hackerip
do
echo "hacker ip is $logip already login $serverip"|mail -s "SOS" rocdk890@139.com
done
fi