python实现监控站点目录,记录每天更新内容,并写入操作日志,以便查找病毒恶意修改

发布时间 2024-01-06 10:44:34作者: 没用的阿吉是剑神

问题描述:站点需要追溯代码的修改时间,以便尽早发现病毒恶意修改迹象,及时处理

运行环境:linux服务器,宝塔面板

示例代码:一、读取txt的文件路径,依次遍历所有目录下面的文件,并记录文件信息

 

paths.txt路径示例

 

 

# encoding: utf-8
import os
import time
import datetime

now = datetime.datetime.now()
files = open("/www/file/paths.txt", "r")    #paths.txt文件存放所有需要遍历的路径名称
for line in files:
folder_path = "/mnt/wwwroot/" + line.strip() # 不再在末尾添加"/",确保它是指向文件夹而不是根目录
if not os.path.isdir(folder_path): # 检查路径是否为一个存在的目录
continue # 如果不是,则跳过此次循环迭代

fname = now.strftime('%Y%m%d%H%M') + line.strip() + ".txt"      #以时间和文件夹名称创建txt文件
with open('/www/fileslogs/' + fname, 'a') as output_file:
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)    #获取文件路径
file_name = os.path.basename(file_path)     #获取文件名称
file_size = os.stat(file_path).st_size
fomateSize = round(file_size / 1024, 2)    #获取文件大小,单位转换为KB,保存2位小数
last_modified = os.path.getmtime(file_path)   
lastChange = str(datetime.datetime.fromtimestamp(last_modified))   #最后修改时间
if  'temp' not in root and 'cache' not in root:   #排除不需要统计的目录
with open('/www/fileslogs/' +fname, 'a') as file:
file.write("FN- " + file_name + " S- " + str(fomateSize) + "KB LC- " + lastChange + " FP- " + file_path + "\n")    #写日志

二、获取每天更新的数据并记录

# encoding: utf-8
import re
import os
import time
import datetime
now = datetime.datetime.now()
fname = now.strftime('%Y%m%d%H%M') + ".txt"
today =now.strftime('%Y-%m-%d')   
def search_keyword_forline(filepath, keyword):
with open(filepath, 'r') as file:
lines = file.readlines()
result = []
for line in lines:
if re.search(keyword, line):
result.append(line)
return result

def search_keyword(folder_path, keyword):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
content = f.read()
if 'Runtime' not in file_path:
if keyword in content:
# print("在文件 {} 中找到了关键字 '{}'".format(file_path, keyword))
result = search_keyword_forline(file_path, keyword)
# print("结果:")
for line in result:
# print(line)
with open('/www/wwwlogs/changelog/' + fname, 'a') as output_file:    #写入日志
output_file.write(line + "\n")

search_keyword('/www/fileslogs/',today)    #路径为上面的记录日志路径,查询当天改变的数据并记录

 三、设置宝塔定时任务执行程序,可设置为每天23:50分执行遍历,23:57执行查询