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 VPS 實戰教學:設定 SSH 登入郵件通知,守護伺服器安全

編輯:Linux 教學

當虛擬私有伺服器(VPS)開啟 SSH 服務並暴露於公網時,便如同在大門上掛了一把鎖,卻將鑰匙藏在門墊下——尤其是仍允許 root 直接登入的情況下,更是為暴力破解攻擊敞開大門。為了第一時間掌握異常登入,建議為每一次成功的 SSH 登入配置自動郵件警示,記錄登入帳號、時間與來源 IP 等關鍵資訊,構建起主動防禦的第一道防線。

適用環境

本教學適用於 CentOS 6/7、RHEL 6/7 等主流企業級 Linux 發行版。

操作步驟

1. 以 root 身分登入伺服器

透過 SSH 客戶端連線至您的 VPS,確保擁有最高權限進行系統配置。

2. 全域配置:所有使用者生效

編輯全域環境腳本 /etc/bashrc,使警示機制對 root 及一般使用者同時生效:

[root@vps ~]# vi /etc/bashrc

在檔案末尾加入下列指令(請將郵箱替換為您的實際接收信箱):

echo 'ALERT – Root Shell Access (your.domain.com) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" your@email.com

3. 僅針對 root 使用者

若僅需監控 root 登入,請編輯 root 的個人配置檔 /root/.bashrc:

[root@vps ~]# vi /root/.bashrc

同樣在檔案尾部加入上述郵件指令。配置完成後的 .bashrc 範例如下:

# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
echo 'ALERT – Root Shell Access (your.domain.com) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" your@email.com

4. 指定特定一般使用者

以使用者 chendexin 為例,編輯其家目錄下的 .bashrc:

[root@vps ~]# vi /home/chendexin/.bashrc

加入郵件指令,接收信箱可依需求設定不同地址:

echo 'ALERT – Root Shell Access (your.domain.com) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" recipient@gmail.com

進階建議

  • 搭配 fail2ban 自動封鎖異常 IP,實現「預警+阻斷」雙重防護。
  • 建議禁止 root 直接 SSH 登入(PermitRootLogin no),改以一般帳號登入後再 su - 切換,降低攻擊面。
  • 定期檢查郵件日誌與 /var/log/secure,排查可疑登入模式。

部署完成後,嘗試重新登入 SSH 驗證郵件是否正常送達。若未收到郵件,請確認系統已安裝並正確配置 mailx 或 postfix 等郵件發送服務。

Copyright © Windows教程網 All Rights Reserved