登錄Linux服務器時觸發郵件提醒

 

目前,客戶只能在發現數據或者虛擬機被惡意侵入或者用戶的誤操做致使了數據的丟失以後,採起善後的手段,可是並無法作到提早的預警。那麼經過 PAM 模塊,就能夠實現用戶登陸及獲取root 權限時,經過郵件的方式進行通知。以實現預先知道、預先警戒的目標,同時下降受影響的範圍。如下是經過 PAM 模塊實現的郵件通知用戶登陸的功能linux

 

1.建立腳本(/tmp/ssh/login_notify.sh),備註:該腳本可存放在服務器的任意位置,可是須要將後續的路徑指定好bash

[root@hlmcen75n1-gen-um waagent]# cat /tmp/ssh/login_notify.sh 
#!/bin/bash

[ "$PAM_TYPE" = "open_session" ] || exit 0
{
echo "User: $PAM_USER"
echo "Ruser: $PAM_RUSER"
echo "Rhost: $PAM_RHOST"
echo "Service: $PAM_SERVICE"
echo "TTY: $PAM_TTY"
echo "Date: `date`"
echo "Server: `uname -a`"
} | mail -s "`hostname -s` $PAM_SERVICE login: $PAM_USER" user@yourdomain.com

 

2.給腳本(/tmp/ssh/login_notify.sh)添加可執行權限服務器

[root@hlmcen75n1-gen-um ~]# chmod +x /tmp/ssh/login_notify.sh

 

3.編輯文件(/etc/pam.d/sshd),在文件最後追加一行(session optional pam_exec.so debug /bin/bash /tmp/ssh/login_notify.sh)session

[root@hlmcen75n1-gen-um waagent]# cat /etc/pam.d/sshd 
#%PAM-1.0
auth       required    pam_sepermit.so
auth       substack     password-auth
auth       include      postlogin
# Used with polkit to reauthorize users in remote sessions
-auth      optional     pam_reauthorize.so prepare
account    required     pam_nologin.so
account    include      password-auth
password   include      password-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    required     pam_namespace.so
session    optional     pam_keyinit.so force revoke
session    include      password-auth
session    include      postlogin
# Used with polkit to reauthorize users in remote sessions
-session   optional     pam_reauthorize.so prepare
session optional pam_exec.so debug /bin/bash /tmp/ssh/login_notify.sh

 

4.至此,每個用戶登陸都會發郵件通知給收件人,內容包括用戶名以及登陸的 IP 地址信息。若是遇到陌生 IP,那麼就要注意。以此來判斷該虛擬機是否正在遭受攻擊,郵件示例以下:dom

 

5.同理,你能夠在把上述腳本應用到 /etc/pam.d/ 其餘模塊中,好比 sudo,login 等,來進行監控ssh

 

參考連接:https://docs.azure.cn/zh-cn/articles/azure-operations-guide/virtual-machines/linux/aog-virtual-machines-linux-security-reinforceide

相關文章
相關標籤/搜索