import os
from openpyxl import load_workbook, Workbook
import smtplib
# 邮件正文
from email.mime.text import MIMEText
# 邮件头
from email.header import Header
# 登录邮箱
smtp_login = smtplib.SMTP_SSL('smtp.263.net', 465)
smtp_login.login('邮箱地址', '密码')
os.system('>test')
# ip1 ip2 ip3 为zk集群所在ip
for i in ['ip1 ', 'ip2 ', 'ip3 ']:
command = 'echo ruok |nc ' + i + '2181 >>test'
command_1 = 'ansible ' + i + '-m script -a ' + '/home/script/zk_shell.sh' + ' |egrep "*节点\\"$" >>test'
os.system(command)
os.system(command_1)
f1 = open(r'test', encoding='utf-8', mode='r')
nr = f1.readlines()
testnr = '<thead>'
for line in nr:
testnr += f'<th>{line}</th>'
testnr += '</thead>'
smtp_html = f'''
<table border = '1px solid black'>
{testnr}
</table>
'''
msg = MIMEText(smtp_html, 'html', 'utf-8')
msg['From'] = Header('大白胖子', 'utf-8')
msg['To'] = Header('运维人员', 'utf-8')
msg['Subject'] = Header('zk监控', 'utf-8')
# 发邮件
smtp_login.sendmail('发件箱', ['收件箱'], msg.as_string())
f1.close()
/home/script/zk_shell.sh得脚本如下
$ZK_HOME为配置好的系统环境变量
source /etc/profile
#!/bin/bash
i=`hostname -I`
command_path=`$ZK_HOME/zkServer.sh status`
echo $command_path|awk -F": " 'END{print $NF}'>test.txt
status_1=`cat test.txt`
if [[ $status_1 == follower ]]
then
echo $i'follower节点'
elif [[ $status_1 == leader ]]
then
echo $i'leader节点'
else
echo $i'不正常节点'
fi