背景
由于工作中需要使用linux监控应用程序,失败需要告警处理,在网上找了半天,发现没有一篇文章把在linux 使用shell 脚本发送邮件,于是找了很多资料,东拼西凑的,成功的使用mailx发送邮件,现总结如下
一、安装
yum install mailx -y
二、配置参数
vim /etc/mail.rc
set from=data_monitor@xxx.com
set smtp=smtps://smtp.exmail.qq.com:465
set smtp-auth-user=data_monitor@xxx.com
set smtp-auth-password=xxxxx
set smtp-auth=login
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb
由于阿里云封闭了25端口,所以使用465端口发送
三、测试
echo hello word | mail -s " title" xxxx@xxx.com
成功
有个小插曲由于系统的域名是data-collect-7,一直显示如下错误,
可能是不符合命名规则吧,解决方案
vim /etc/hosts 添加一行
ip data-collect-7 data.collect7
参考:https://blog.51cto.com/hades02/1734336
四、解决证书问题
尽管邮件发送成功但是总是报这个错误
进入root用户
[root@data-collection-7 ~]#mkdir ~/.certs/
[root@data-collection-7 ~]#echo -n | openssl s_client -connect smtp.exmail.qq.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/qq.crt
[root@data-collection-7 ~]#certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
[root@data-collection-7 ~]# certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
[root@data-collection-7 ~]# certutil -L -d /root/.certs
[root@data-collection-7 ~]# cd /root/.certs/
[root@data-collection-7 .certs]# certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ./ -i qq.crt
Notice: Trust flag u is set automatically if the private key is present.
最后 vim /etc/mail.rc 将set nss-config-dir=/etc/pki/nssdb替换为set nss-config-dir=/root/.certs
#set nss-config-dir=/etc/pki/nssdb
set nss-config-dir=~/.certs
# 注意用户权限问题普通用户是访问不到root用户下的认证,需要拷贝一份到普通用户的根目录下 cp -r /root/.certs /home/hadoop 修改所有者权限 chown -R hadoop:hadoop /home/hadoop/.certs
详细参考:https://blog.51cto.com/13162375/2173007
参考:【1】https://stackoverflow.com/questions/16799407/mailx-and-gmail-nss-config-dir
【2】https://developer.aliyun.com/ask/236538?spm=a2c6h.13524658
【3】https://blog.51cto.com/13162375/2173007
附监控任务失败发生邮件的shell脚本
#!/bin/bash
while :
do
processExist=`ps aux|grep 'com.zendesk.maxwell.Maxwell --config conf/zebra.properties' |grep -v "grep"`
#echo $processExist
nowtime=$(date "+%Y-%m-%d %H:%M:%S")
if [[ -z $processExist ]] ; then
#if [ "$processExist" ] ; then
sh xxx.sh
echo "xxx任务异常,已重启,若频繁告警请登录服务器查看原因" | mail -s "data-collect-x xxx任务异常重启" xxx@xxxx.com
echo $nowtime "the process is restarted !"
else
echo $nowtime "the process is running !"
fi
sleep 30
done
备份
安装sendmail
yum install -y sendmail
systemctl start sendmail.service #启动
systemctl restart sendmail.service #重启
systemctl status sendmail.service # 状态
systemctl stop sendmail.service #停止
systemctl enable sendmail.service #服务器重启生效