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 SSH 登入郵件通知設定(含 Postfix/外部 SMTP 方案)

編輯:Linux 教學

伺服器暴露 SSH 於公網極易遭暴力破解,設定「登入成功即寄信通知管理員」是基礎防禦之一。本文提供三種範圍(所有用戶、僅 root、特定用戶)的設定方式,並解決 mail 指令常見的 IPv6、Postfix 設定問題,最後介紹更穩定的「外部 SMTP 直送」方案。

方案一:修改 Shell 設定檔(最簡單,但依賴本機 mail 系統)

1. 所有 SSH 用戶

# vi /etc/bashrc
# 末尾加入
echo 'ALERT - SSH Login on $(hostname) at $(date) from $(who | awk "{print \$5}" | tr -d "()")' \
| mail -s "SSH Login: $(whoami)@$(hostname)" admin@example.com

2. 僅 root

# vi /root/.bashrc
# 末尾加入同上指令

3. 特定用戶(如 bin2u)

# vi /home/bin2u/.bashrc
# 末尾加入同上指令

立即生效

source /etc/bashrc   # 或對應檔案
# 重新 SSH 登入測試

常見問題:mail 指令報 IPv6 錯誤

send-mail: warning: inet_protocols: IPv6 support is disabled
postdrop: warning: inet_protocols: IPv6 support is disabled

修正 Postfix 僅用 IPv4

# vi /etc/postfix/main.cf
# 找到 inet_protocols = all
# 改為
inet_protocols = ipv4

# 重啟
systemctl restart postfix

驗證

echo "test" | mail -s "test" admin@example.com

方案二:使用外部 SMTP 直送(推薦,不依賴本機 MTA)

編輯 /etc/mail.rc(或 ~/.mailrc),設定 SMTP 認證:

set from=your@139.com
set smtp=smtp.139.com
set smtp-auth-user=your
set smtp-auth-password=yourpass
set smtp-auth=login
set smtp-use-starttls=yes   # 若支援 STARTTLS
set ssl-verify=ignore       # 若憑證自簽

之後 mail 指令會直接經由 139/Gmail/公司 SMTP 發送,繞過本機 Postfix/Sendmail,極大降低「信件被擋、隊列卡住、IP 信譽差」等風險。

進階:僅通知「互動式登入」避免雜訊

SCP、SFTP、Git over SSH、Ansible 等非登入連線也會觸發 .bashrc。若只想通知真人登入,可在腳本開頭判斷:

# 僅在互動式 shell 且有 SSH_CONNECTION 時發信
if [[ $- == *i* ]] && [[ -n $SSH_CONNECTION ]]; then
    IP=$(echo $SSH_CONNECTION | awk '{print $1}')
    echo "User $(whoami) logged in from $IP at $(date)" \
    | mail -s "SSH Login Alert: $(whoami)@$(hostname)" admin@example.com
fi

替代方案:系統層面 PAM + 脚本

更乾淨的做法是使用 pam_exec.so 呼叫獨立腳本,不汙染 Shell 環境:

# /etc/pam.d/sshd 加入
session optional pam_exec.so seteuid /usr/local/bin/ssh-login-alert.sh
#!/bin/bash
# /usr/local/bin/ssh-login-alert.sh
if [[ $PAM_TYPE == "open_session" ]] && [[ -n $PAM_RHOST ]]; then
    echo "User $PAM_USER from $PAM_RHOST at $(date)" \
    | mail -s "SSH Login: $PAM_USER@$(hostname)" admin@example.com
fi
  • 需 chmod +x /usr/local/bin/ssh-login-alert.sh
  • 不影響非互動連線、不依賴特定 Shell。

測試與驗證清單

  1. 本機 echo test | mail -s test admin@example.com 收到信。
  2. SSH 重新登入,收到通知信(檢查垃圾信箱)。
  3. scp file host:、ssh host true 不應收到信(若用 PAM 方案)。
  4. mailq 確認無滯留信件。
SSH 登入通知是「事後發現入侵」的最後一道防線;真正的防禦應優先:禁用密碼認證、強制金鑰登入、Fail2Ban、非標準埠、防火牆限制來源 IP。通知機制只是讓你第一時間知道有人進來了。
Copyright © Windows教程網 All Rights Reserved