服务器环境: centos7
python版本:3
思路:
通过python脚本去扫描服务器上的日志,如果发现了日志文件有新的改动, 就把新增加的文件内容通过企微机器人推到企微群中,
下面是 把python 脚本在 服务器中创建成一个服务,并且开机启动
linux 服务器步骤
1. 创建 systemd 服务文件
vim /etc/systemd/system/error_log_push.service
error_log_push.service
[Unit]
Description=Error Log Push Service
After=network.target
[Service]
User=root
Group=root
WorkingDirectory=/data/python/
ExecStart=/usr/bin/python3 /data/python/error_log_push.py
Restart=always
Environment="PATH=/usr/bin:/usr/local/bin"
Environment="PYTHONUNBUFFERED=1"
[Install]
WantedBy=multi-user.target
注意:
WorkingDirectory: python 文件的目录
/data/python/error_log_push.py: python 文件的全路径
error_log_push.py
import os
import time
import requests
from datetime import datetime
# scanner_log = 'F:\\python\\first-demo\\errorpush\\log-error.log'
# tk_andeng_platform_log = 'F:\\python\\first-demo\\errorpush\\log-error.log'
# tk_platform_log = 'F:\\python\\first-demo\\errorpush\\log-error2.log'
scanner_log = '/data/logs/scanner-server/log_error.log'
tk_andeng_platform_log = '/data/logs/tk-andeng-platform/log_error.log'
tk_platform_log = '/data/logs/tk-platform/log_error.log'
file_last_read_dict = {}
file_last_update_dict = {}
files = [scanner_log, tk_platform_log, tk_andeng_platform_log]
today_str = datetime.now().strftime("%Y-%m-%d")
def init_dict():
global file_last_read_dict, file_last_update_dict
file_last_read_dict = {scanner_log: '', tk_platform_log: '', tk_andeng_platform_log: ''}
file_last_update_dict = {scanner_log: 0, tk_platform_log: 0, tk_andeng_platform_log: 0}
def send_log_to_api(content, file_name):
# 构建请求的 URL 和数据
url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=12d96410-75fe-4c7c-a5b1-fcd51122d29f"
data = {
"msgtype": "text",
"text": {
"content": file_name + ":\n" + content
}
}
try:
response = requests.post(url, json=data)
if response.status_code == 200:
print(f"Log from {file_name} sent successfully")
else:
print(f"Failed to send log from {file_name}, status code:", response.status_code)
except Exception as e:
print(f"Error sending log from {file_name}:", e)
def handle_file():
for file_name in files:
path_getmtime = os.path.getmtime(file_name)
print(f"{file_name}文件 修改时间:{path_getmtime}")
if file_last_update_dict[file_name] == path_getmtime:
print("文件没有发生变化")
continue
file_last_update_dict[file_name] = path_getmtime
print("文件发生变化")
with open(file_name, 'r', encoding='utf-8') as file:
# 移动到文件的最后一行
file_value = file_last_read_dict[file_name]
if file_value:
print("记录不为空,从上次位置开始")
file.seek(file_value)
else:
file.seek(0, 2)
file_last_read_dict[file_name] = file.tell() # 更新文件位置
print(f"开始读取文件内容: {file_name}...")
lines = file.readlines()
if not lines:
print(f"没有新的文件内容在 {file_name}, waiting...")
continue
tell = file.tell()
print(f"文件位置:{tell}")
file_last_read_dict[file_name] = tell # 更新文件位置
# 调用接口,发送消息
content = ''.join(lines)
# print(f"New content:{content}")
send_log_to_api(content, file_name)
def pre_process():
global today_str
now_day = datetime.now().strftime("%Y-%m-%d")
if today_str != now_day:
print("新的一天了")
today_str = now_day
init_dict()
if __name__ == "__main__":
init_dict()
while True:
print("开始监控文件")
try:
# 5秒执行一次
time.sleep(5)
pre_process()
handle_file()
except Exception as e:
# 这里处理捕获到的异常
print(f"发生了一个错误: {str(e)}")
send_log_to_api(str(e), "<<python程序错误>>")
2. 加载服务文件
systemctl daemon-reload
3. 启动服务
systemctl start error_log_push.service
4. 设置开机启动
systemctl enable error_log_push.service
1058

被折叠的 条评论
为什么被折叠?



