python获取Windows事件日志并发送到企业微信邮箱

python获取Windows事件日志并发送到企业微信

开启企业微信的邮箱服务

  1. 登录企业微信邮箱
    收件人和被抄送方的都需要开启服务。
  2. 找到"设置"-"收发信设置"
  3. 开启服务
  4. 点击保存更改
  5. 生成客户端专用密码(发送方需要生成这个密码)

导入所需模块

python 复制代码
import os  # 用于获取系统路径
import time  # 用于获取当前时间
import shutil  # 用于删除文件夹
import zipfile  # 用于压缩文件夹
import smtplib  # 用于发送邮件
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header

获取系统事件日志并压缩

  1. 复制C:\Windows\System32\winevt\Logs下的内容,整个Logs文件夹复制并粘贴到桌面,并将Logs的名称改成当前时间+Logs
python 复制代码
# 获取桌面路径
desktop_path = os.path.join(os.environ['USERPROFILE'], 'Desktop')

# 定义输出文件和错误日志文件的保存路径
error_log_path = os.path.join(desktop_path, 'error.log')

# 获取当前时间
current_time = time.strftime('%Y%m%d%H%M%S', time.localtime())

# 在桌面上创建输出文件和错误日志文件
if not os.path.exists(error_log_path):
    with open(error_log_path, 'w', encoding='utf-8'):
        pass

# 复制C:\Windows\System32\winevt\Logs\下的文件包含Logs文件夹的名称
# 给Logs文件夹重命名为当前时间+Logs,文件放在桌面上

try:
    source_folder = 'C:\\Windows\\System32\\winevt\\Logs'
    target_folder = os.path.join(desktop_path, current_time + 'Logs')

    # 复制文件夹到桌面,并重命名为当前时间+Logs
    shutil.copytree(source_folder, target_folder)
    with open(error_log_path, 'a', encoding='utf-8') as f:
        f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + f'日志复制成功\n'))

except Exception as e:
    with open(error_log_path, 'a', encoding='utf-8') as f:
        f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + f'日志复制失败:' + str(e) + '\n'))
  1. 将桌面的当前时间+Logs文件夹内的文件包含文件夹一起打包成一个.zip文件
python 复制代码
# 将重命名的文件夹打成zip压缩包,压缩包放到桌面上
zip_file_name = current_time + 'Logs.zip'
zip_file_path = os.path.join(desktop_path, zip_file_name)

# 压缩文件夹
try:
    with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zf:

        # 遍历文件夹 root:当前目录, dirs:子目录列表, files:文件列表
        for root, dirs, files in os.walk(os.path.join(desktop_path, current_time + 'Logs')):
            for file in files:
                # 创建文件的绝对路径
                file_path = os.path.join(root, file)
                # 创建文件相对于压缩包根目录的相对路径
                relative_path = os.path.relpath(file_path, os.path.dirname(zip_file_path))
                # 将文件添加到 zf 中
                zf.write(file_path, relative_path)
except Exception as e:
    with open(error_log_path, 'a', encoding='utf-8') as f:
        f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + f'日志备份压缩失败:' + str(e) + '\n'))

发送到企业微信邮箱

python 复制代码
# 企业微信的邮件服务器是smtp.exmail.qq.com
# 企业微信的邮件服务器端口是465
smtp_server = 'smtp.exmail.qq.com'
smtp_port = 465

# 登录信息
sender = '发送者的邮箱.com'
password = '发送者的邮箱的客户端密码'
receiver = '接受者的邮箱.com'

# 邮件主题和内容
subject = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + 'Windows日志备份'
content = f'附件为{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}时的Windows日志备份文件'
# 邮件附件
attachment = zip_file_path
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = Header(sender)
msg['To'] = Header(receiver)
# 这里这个抄送者邮箱会显示在邮件头处
msg["Cc"] = Header('抄送者的邮箱.com', 'utf-8')
msg['Subject'] = Header(subject)

# 邮件正文
msg.attach(MIMEText(content, 'plain', 'utf-8'))

# 附件
with open(attachment, 'rb') as f:
    # 设置附件的MIME和文件名 name参数是邮件中显示的名字
    attach = MIMEApplication(f.read(), Name=os.path.basename(attachment))
    # 加上必要的头信息 application/zip是MIME类型
    attach['Content-Type'] = 'application/zip'
    # content-disposition是MIME协议的扩展,表示以何种方式展示附件
    attach['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(attachment))
    msg.attach(attach)

# 发送邮件
try:
    # 连接到邮箱服务器
    smtp_obj = smtplib.SMTP_SSL(smtp_server, smtp_port)
    # 登录邮箱
    smtp_obj.login(sender, password)
    # 发送邮件,还要发送给cc人
    smtp_obj.sendmail(sender, [receiver, '抄送者的邮箱.com'], msg.as_string())
    # 关闭连接
    smtp_obj.quit()
except smtplib.SMTPException as e:
    with open(error_log_path, 'a', encoding='utf-8') as f:
        f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + f'邮件发送失败:' + str(e) + '\n'))

删除桌面多余文件夹和压缩包

python 复制代码
# 删除重命名的文件夹
try:
    if os.path.exists(os.path.join(desktop_path, current_time + 'Logs')):
        shutil.rmtree(os.path.join(desktop_path, current_time + 'Logs'))
except Exception as e:
    with open(error_log_path, 'a', encoding='utf-8') as f:
        f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + f'日志备份文件夹删除失败:' + str(e) + '\n'))
# 6. 删除压缩包
try:
    if os.path.exists(zip_file_path):
        os.remove(zip_file_path)
except Exception as e:
    with open(error_log_path, 'a', encoding='utf-8') as f:
        f.write(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + f'日志备份压缩包删除失败:' + str(e) + '\n'))

打包成.exe小程序

python 复制代码
# 控制台执行这句,没有pyinstaller库先运行pip install pyinstaller
# -F 打包成一个可执行文件
# -w运行时不显示命令框 
# -i 为.exe生成图标
# --name 设置可执行文件的名称
# xxx.py 表示打包哪一个python文件
pyinstaller -F -w -i f3.ico --name=sendLogsToQW001.exe sendLogsToQW.py

运行

这个可执行文件需要以管理员权限运行

相关推荐
Java手札6 分钟前
Windows下Golang与Nuxt项目宝塔部署指南
开发语言·windows·golang
梓羽玩Python21 分钟前
开源AI代理爆火!Suna:3天内新增5.5K+标星,自然对话驱动的自动化神器!
人工智能·python·github
心灵宝贝25 分钟前
Postman-win64-7.2.2 安装教程(Windows 64位详细步骤)
windows·测试工具·postman
咖啡调调。26 分钟前
模板引擎语法-过滤器
python·django·sqlite
Ankie Wan36 分钟前
notepad++技巧:查找和替换:扩展 or 正则表达式
python·正则表达式·notepad++
带娃的IT创业者36 分钟前
《AI大模型趣味实战》智能Agent和MCP协议的应用实例:搭建一个能阅读DOC文件并实时显示润色改写过程的Python Flask应用
人工智能·python·flask
JavaEdge在掘金44 分钟前
启动nginx报错,80 failed (97: Address family not supported by protocol)
python
纪元A梦1 小时前
华为OD机试真题——绘图机器(2025A卷:100分)Java/python/JavaScript/C++/C/GO最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
程序员小远1 小时前
接口测试和单元测试详解
自动化测试·软件测试·python·测试工具·单元测试·测试用例·接口测试
Tech Synapse1 小时前
电商商品推荐系统实战:基于TensorFlow Recommenders构建智能推荐引擎
人工智能·python·tensorflow