我使用一个python3日志解析器来过滤日志并将电子邮件作为python2附件发送到outlook,虽然这在python2中很好,但是python3我得到了一个警告。
在这方面的任何帮助将是非常感谢的。
Python解析(pyParser.py)
#!/usr/bin/python3
import sys
import re
from subprocess import Popen, PIPE
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg_body = ''
node_name = ''
mailstr = """<html><head></head><body>
<table border=1>
<tr>
<th bgcolor=fe9a2e>Hostname</th>
<th bgcolor=fe9a2e>Service</th>
</tr>
"""
fh=open(sys.argv[1],"r")
for line in fh:
pat_match_next=re.search("^\s*\"stdout.*", line)
if pat_match_next:
continue
pat_match=re.search("^.*\"?Service Status:\s+(.*)(\s+\S+)\"?.*$", line)
if pat_match:
msg_body = pat_match.group(1)
node_name = pat_match.group(2)
mailstr += """<TR><TD bgcolor=fe9a2e>""" + node_name + """</TD>\n"""
mailstr += """<TR><TD><TD>""" + msg_body + node_name + """</TD></TD></TR>\n"""
mailstr += """</body></html>"""
mailp = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
msg = MIMEMultipart('alternative')
msg['To'] = ""
msg['Cc'] = ""
msg['Subject'] = "HealthCheck Report"
msg['From'] = ""
msg1 = MIMEText(mailstr, 'html')
msg.attach(msg1)
mailp.communicate(msg.as_string())
日志文件(HealthCheck_log):
HostName: fsxdb01.example.com
Service Status: NTP is not Running on the host fsxdb01.example.com
Service Status: NSCD is not Running on the host fsxdb01.example.com
Service Status: Sendmail is Running on the host fsxdb01.example.com
Service Status: Automount is Running on the host fsxdb01.example.com
Service Status: Filesystem For root (/) is not normal and 47% used on the host fsxdb01.example.com
Service Status: Filesystem For Var (/var) is not normal and 68% used on the host fsxdb01.example.com
Service Status: Filesystem For tmp (/tmp) is normal on the host fsxdb01.example.com
当我对日志文件运行上面的脚本时,我得到了如下所示的警告。
$ ./pyParser.py healthCheck_log
Traceback (most recent call last):
File "./pyParser.py", line 40, in <module>
mailp.communicate(msg.as_string())
File "/usr/lib64/python3.6/subprocess.py", line 848, in communicate
self._stdin_write(input)
File "/usr/lib64/python3.6/subprocess.py", line 801, in _stdin_write
self.stdin.write(input)
TypeError: a bytes-like object is required, not 'str'
No recipient addresses found in header
另一个问题不是关于运行,而是关于邮件格式,如主机名和消息对齐成一行,并创建一个空白单元格。
应:
发布于 2022-04-10 23:24:05
来自子进程的文档 (在几个地方提到):
如果指定了编码或错误,或者文本(也称为universal_newlines)为真,则文件对象stdin、stdout和stderr将使用调用中指定的编码和错误或io.TextIOWrapper的默认值以文本模式打开。 ..。 如果不使用文本模式,则stdin、stdout和stderr 将作为二进制流打开。不执行编码或行结束转换。
所以在python3里试试
mailp.communicate(msg.as_bytes())
至于html:
mailstr += """<TD>""" + msg_body + node_name + """</TD></TR>\n"""
当然,最好使用f-字符串,甚至像jinja2
这样的模板引擎,而不是连接。
https://stackoverflow.com/questions/71823702
复制