Linux配置root登陆时发送邮件到指定邮箱

出于安全考虑,需要监控部分敏感主机的root账号访问情况,于是实现root登录时发送邮件到指定邮箱。

提前明确:

发件箱、发件箱授权码、发件箱smtp地址、收件箱


第一步 申请邮箱授权码

选择腾讯企业邮箱,登录发件箱账号后,绑定微信,启用安全登录,选择“客户端专用密码-生成新密码”,此即授权码。

Linux配置root登陆时发送邮件到指定邮箱

参考:https://www.yiyisoft.com/news/402.html


第二步 配置邮件发送

编辑/etc/mail.rc,增加如下内容

set [email protected]    #发件箱
set smtp=smtp.exmail.qq.com               #smtp地址,腾讯企业邮就是这个了
set [email protected]
set smtp-auth-password=vT6K1234543XdsqV   ##<--这里填的是邮箱授权码
set smtp-auth=login

测试配置效果

echo Hello World | mail -s test [email protected]

收件箱[email protected]即可收到主题test、内容Hello World的邮件。

PS:最好采用同一服务商的邮箱,否则可能出现互相屏蔽的情况,比如腾讯与网易,原因你懂的。

参考:https://blog.****.net/ipenx/article/details/78441291


第三步 配置账号访问时发送邮件

如果要监控所有账号登陆,配置/etc/bashrc;监控指定账号,在该账号默认目录下,编辑.bashrc,我要监控的是root,加入如下内容

echo "ALERT - Root Shell Access (`hostname`) on:" `date` `who` | mail -s "`hostname` Root Access from `who | cut -d'(' -f2 | cut -d')' -f1`" [email protected]

即时生效:source .bashrc    

再次使用root登录时,[email protected]即可收到来自[email protected]的邮件。

参考:https://www.jb51.net/LINUXjishu/336236.html


报错:
Jun 11 13:40:56 VM_13_11_centos postfix/postqueue[1558]: warning: inet_protocols: IPv6 support is disabled: Address family not supported by protocol
Jun 11 13:40:56 VM_13_11_centos postfix/postqueue[1558]: warning: inet_protocols: configuring for IPv4 support only
修改/etc/postfix/main.cf如下参数
inet_protocols = all 改为 inet_protocols =ipv4
重启服务:
service postfix restart


报错:could not connect: Connection timed out

"/root/dead.letter" 11/305
. . . message not sent.
排查1:smtp服务器地址dns解析无误
排查2:smtp服务器端口25是否可以访问;
排查结果:25端口不通
PS:smtp端口知识延伸:smtp涉及三个端口:25 587 465;

解决:要么解决25端口不通的问题,要么参考如下改用smtps:

查看/etc/postfix/master.cf
smtp inet n - n - - smtpd
查看/etc/services里面smtp相关465端口ok
urd 465/tcp smtps # URL Rendesvous Directory for SSM / SMTP over SSL (TLS)
配置ssl,修改/etc/mail.rc
set smtp=smtps.exmail.qq.com               #smtp地址,腾讯企业邮就是这个了
set ssl-verify=ignore #ssl认证方式
set nss-config-dir=/root/.certs #证书所在目录

请求数字证书(这里用的qq邮箱,所以向qq请求证书)
mkdir -p /root/.certs/
echo -n | openssl s_client -connect smtp.qq.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/qq.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ~/.certs/./ -i qq.crt
certutil -L -d /root/.certs
如果未请求证书,将报错:Error in certificate: Peer's certificate issuer is not recognized.

其他问题排查:
1、查看防火墙是否对相应端口有限制,修改防火墙策略
-A INPUT -p tcp -m multiport --dports 465,25 -j ACCEPT
2、邮箱是否开启smtp

邮箱开启smtp
如果遇到,503错误,smtp-server: 535 Error
  • 1
那代表你的邮箱还没开启smpt服务。 
例如,QQ邮箱登录后,设置–>帐号–>pop3/smtp,开启,然后QQ邮箱还会给出授权码,就是上面配置时候填的smtp-auth-passwd。