制度落实不严格,核心在于缺乏持续、客观的检查与反馈机制。人工检查存在主观性强、效率低、易遗漏等问题。技术解决方案的核心是:将制度条款转化为可执行的自动化检查规则,实现持续监控与即时告警。
本方案基于轻量级技术栈,无需复杂中间件,通过脚本与定时任务即可构建。系统由三个核心模块构成:规则引擎、检查执行器、报告生成器。
操作系统:Linux (Ubuntu 20.04 LTS) 或 Windows Server 2019+。确保拥有Python 3.8+环境。执行以下命令安装基础依赖:
Ubuntu/Debian:
sudo apt update
sudo apt install python3-pip git -y
pip3 install pandas openpyxl schedule python-dotenv
Windows (PowerShell 管理员模式):
choco install python git -y
pip install pandas openpyxl schedule python-dotenv
在项目根目录创建rules文件夹,并在其中创建file_rules.json,将档案制度具体条款转化为JSON格式的检查规则。
{
"archive_rules": [
{
"rule_id": "RULE-001",
"rule_name": "文件命名规范检查",
"description": "档案文件必须遵循‘部门_日期_事项_版本.pdf’格式",
"target_path": "/data/archives//.pdf",
"check_type": "regex_pattern",
"pattern": "^[A-Za-z]{2,10}_\\d{8}_.+_v\\d+\\.pdf$",
"severity": "high"
},
{
"rule_id": "RULE-002",
"rule_name": "存储期限检查",
"description": "永久保存档案不得存放在‘temp’目录下",
"target_path": "/data/archives//",
"check_type": "path_exclude",
"exclude_pattern": "/temp/",
"severity": "critical"
},
{
"rule_id": "RULE-003",
"rule_name": "元数据完整性检查",
"description": "PDF档案必须包含‘标题’、‘作者’、‘创建日期’元数据",
"target_path": "/data/archives//.pdf",
"check_type": "metadata_check",
"required_fields": ["title", "author", "creation_date"],
"severity": "medium"
}
]
}
此配置文件定义了三条规则:命名规范、路径排除、元数据检查。target_path使用通配符匹配目标文件,severity定义违规严重等级。
创建check_engine.py文件,编写核心检查逻辑。
import os
import json
import re
from pathlib import Path
import PyPDF2 需安装: pip install PyPDF2
import pandas as pd
from datetime import datetime
class ArchiveComplianceChecker:
def __init__(self, rules_file='rules/file_rules.json'):
with open(rules_file, 'r', encoding='utf-8') as f:
self.rules = json.load(f)['archive_rules']
self.violations = []
def run_checks(self, base_path='/data/archives'):
"""执行所有规则检查"""
for rule in self.rules:
if rule['check_type'] == 'regex_pattern':
self._check_regex(rule, base_path)
elif rule['check_type'] == 'path_exclude':
self._check_path_exclude(rule, base_path)
elif rule['check_type'] == 'metadata_check':
self._check_metadata(rule, base_path)
return self.violations
def _check_regex(self, rule, base_path):
"""规则1:正则表达式匹配检查"""
pattern = re.compile(rule['pattern'])
for file_path in Path(base_path).rglob('.pdf'):
if not pattern.match(file_path.name):
self.violations.append({
'rule_id': rule['rule_id'],
'file_path': str(file_path),
'issue': f"文件名不符合规范: {file_path.name}",
'severity': rule['severity'],
'timestamp': datetime.now().isoformat()
})
def _check_path_exclude(self, rule, base_path):
"""规则2:路径排除检查"""
exclude_keyword = rule['exclude_pattern'].split('/')[1] 提取'temp'
for file_path in Path(base_path).rglob(''):
if exclude_keyword in str(file_path.parts):
self.violations.append({
'rule_id': rule['rule_id'],
'file_path': str(file_path),
'issue': f"文件错误存储在'{exclude_keyword}'目录中",
'severity': rule['severity'],
'timestamp': datetime.now().isoformat()
})
def _check_metadata(self, rule, base_path):
"""规则3:PDF元数据检查"""
required = rule['required_fields']
for file_path in Path(base_path).rglob('.pdf'):
try:
with open(file_path, 'rb') as f:
pdf_reader = PyPDF2.PdfReader(f)
meta = pdf_reader.metadata
missing = [field for field in required if not getattr(meta, field, None)]
if missing:
self.violations.append({
'rule_id': rule['rule_id'],
'file_path': str(file_path),
'issue': f"缺失必要元数据字段: {', '.join(missing)}",
'severity': rule['severity'],
'timestamp': datetime.now().isoformat()
})
except Exception as e:
self.violations.append({
'rule_id': rule['rule_id'],
'file_path': str(file_path),
'issue': f"读取文件元数据失败: {str(e)}",
'severity': 'high',
'timestamp': datetime.now().isoformat()
})
if __name__ == '__main__':
checker = ArchiveComplianceChecker()
violations = checker.run_checks()
print(f"检查完成,发现 {len(violations)} 条违规记录")
执行器按规则类型调用不同检查方法,并将所有违规记录存储在violations列表中。
创建report_generator.py文件,生成可视化报告并设置定时任务。
import pandas as pd
from check_engine import ArchiveComplianceChecker
import schedule
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
def generate_excel_report(violations, output_file='reports/compliance_report.xlsx'):
"""生成Excel格式的详细违规报告"""
df = pd.DataFrame(violations)
if not df.empty:
按严重等级排序
severity_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
df['severity_num'] = df['severity'].map(severity_order)
df = df.sort_values(['severity_num', 'rule_id'])
df = df.drop('severity_num', axis=1)
写入Excel,不同严重等级使用不同颜色
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name='违规详情', index=False)
worksheet = writer.sheets['违规详情']
设置列宽
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 50)
worksheet.column_dimensions[column_letter].width = adjusted_width
print(f"报告已生成: {output_file}")
else:
print("本次检查未发现违规项")
def send_email_alert(violations, config_file='config/email_config.json'):
"""发送邮件告警(仅在发现严重或关键违规时)"""
critical_violations = [v for v in violations if v['severity'] in ['critical', 'high']]
if not critical_violations:
return
加载邮件配置
with open(config_file, 'r') as f:
config = json.load(f)
msg = MIMEMultipart()
msg['From'] = config['sender']
msg['To'] = ', '.join(config['recipients'])
msg['Subject'] = f"[档案合规告警] 发现 {len(critical_violations)} 条严重违规"
body = "以下档案文件存在严重合规问题,请立即处理:\n\n"
for v in critical_violations[:10]: 最多显示10条
body += f"- [{v['severity'].upper()}] {v['file_path']}\n 问题:{v['issue']}\n\n"
if len(critical_violations) > 10:
body += f"... 还有{len(critical_violations)-10}条未显示,详情请查看附件报告。\n"
msg.attach(MIMEText(body, 'plain'))
添加报告附件
report_file = 'reports/compliance_report.xlsx'
with open(report_file, 'rb') as f:
part = MIMEApplication(f.read(), Name=os.path.basename(report_file))
part['Content-Disposition'] = f'attachment; filename="{os.path.basename(report_file)}"'
msg.attach(part)
发送邮件
with smtplib.SMTP(config['smtp_server'], config['smtp_port']) as server:
server.starttls()
server.login(config['sender'], config['password'])
server.send_message(msg)
print("严重违规告警邮件已发送")
def daily_compliance_check():
"""每日定时执行检查任务"""
print(f"{datetime.now().isoformat()} 开始执行档案合规检查...")
checker = ArchiveComplianceChecker()
violations = checker.run_checks()
generate_excel_report(violations)
send_email_alert(violations)
print(f"{datetime.now().isoformat()} 检查任务完成")
if __name__ == '__main__':
创建必要目录
os.makedirs('reports', exist_ok=True)
os.makedirs('config', exist_ok=True)
配置邮件设置(首次运行需要)
email_config = {
"smtp_server": "smtp.office365.com",
"smtp_port": 587,
"sender": "your_email@company.com",
"password": "your_app_password",
"recipients": ["admin1@company.com", "admin2@company.com"]
}
with open('config/email_config.json', 'w') as f:
json.dump(email_config, f, indent=2)
立即执行一次
daily_compliance_check()
设置每日上午9点自动执行
schedule.every().day.at("09:00").do(daily_compliance_check)
print("定时任务已设置,每日09:00自动执行检查")
while True:
schedule.run_pending()
time.sleep(60)
报告模块生成结构化Excel,并通过邮件自动推送严重告警。定时任务确保检查持续运行。

在服务器上创建项目目录并部署代码。
1. 创建项目目录结构
mkdir -p /opt/archive-compliance/{rules,config,reports,logs}
cd /opt/archive-compliance
2. 将上述三个代码文件复制到该目录
check_engine.py, report_generator.py, file_rules.json
3. 修改文件规则,匹配实际档案路径
编辑 file_rules.json,将所有 target_path 中的 /data/archives 改为实际路径,如 /nas/company_archives
4. 配置邮件参数
编辑 config/email_config.json,填入真实的SMTP服务器和账号信息
运行以下命令验证系统功能:
cd /opt/archive-compliance
python3 check_engine.py
python3 report_generator.py
检查reports/compliance_report.xlsx文件是否生成,并确认内容正确。
创建Systemd服务,实现开机自启与后台运行。
sudo nano /etc/systemd/system/archive-compliance.service
写入以下内容:
[Unit]
Description=Archive Compliance Check Service
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/archive-compliance
ExecStart=/usr/bin/python3 /opt/archive-compliance/report_generator.py
Restart=always
RestartSec=10
StandardOutput=append:/opt/archive-compliance/logs/service.log
StandardError=append:/opt/archive-compliance/logs/error.log
[Install]
WantedBy=multi-user.target
启动并启用服务:
sudo systemctl daemon-reload
sudo systemctl start archive-compliance
sudo systemctl enable archive-compliance
sudo systemctl status archive-compliance 检查运行状态
使用计划任务实现定时执行:
1. 创建批处理文件 run_check.bat
@echo off
cd C:\opt\archive-compliance
python report_generator.py
2. 打开“任务计划程序”
3. 创建基本任务
名称:档案合规每日检查
触发器:每日,09:00
操作:启动程序,程序路径填写 run_check.bat 的完整路径
当档案制度更新或新增检查项时,只需修改file_rules.json文件,无需改动代码。
{
"rule_id": "RULE-004",
"rule_name": "文件大小限制检查",
"description": "单个档案文件不得超过50MB",
"target_path": "/data/archives//",
"check_type": "file_size",
"max_size_mb": 50,
"severity": "medium"
}
def _check_file_size(self, rule, base_path):
"""新增:文件大小检查"""
max_bytes = rule['max_size_mb'] 1024 1024
for file_path in Path(base_path).rglob(''):
if file_path.is_file():
file_size = file_path.stat().st_size
if file_size > max_bytes:
self.violations.append({
'rule_id': rule['rule_id'],
'file_path': str(file_path),
'issue': f"文件大小{file_size//(10241024)}MB超过{rule['max_size_mb']}MB限制",
'severity': rule['severity'],
'timestamp': datetime.now().isoformat()
})
并在run_checks方法中添加对应的条件分支:elif rule['check_type'] == 'file_size': self._check_file_size(rule, base_path)。
系统运行后,通过以下方式验证效果:
通过将制度条款逐一转化为技术规则,本系统实现了档案合规检查的自动化、常态化与客观化,从根本上解决了“落实不严格”问题。所有配置与规则均通过文件管理,维护简单,扩展性强。