每周同步校园站点代码与资料快照(2026-11-27)

由 Acer 自动归档站点代码、部署配置及已验证的论坛资料快照。
This commit is contained in:
JarodLee
2026-11-27 10:22:39 +08:00
parent e54b10a805
commit 84ec422bea
8 changed files with 379 additions and 0 deletions

View File

@@ -52,6 +52,7 @@ try{
if($remotes -contains 'github'){Git @('-C',$source,'remote','set-url','github',$c.github)|Out-Null}else{Git @('-C',$source,'remote','add','github',$c.github)|Out-Null}
Git @('-C',$source,'config','core.sshCommand',$env:GIT_SSH_COMMAND)|Out-Null
Phase 'Collecting deployment sources'
foreach($name in @('report.py','settings.json','Install-Task.ps1','README.md')){CopyChanged ('C:\ProgramData\AcerWeeklyReport\'+$name) ($source+'\deployment\acer\weekly-report\'+$name)}
$web=Split-Path $source
foreach($name in @('default.asp','portal-home.css','bing-wallpaper.asp','system_monitor.html','w.jpg')){CopyChanged ($web+'\'+$name) ($source+'\deployment\acer\web\'+$name)}
CopyChanged 'C:\ProgramData\AcerSystemMonitor\collect.ps1' ($source+'\deployment\acer\services\collect.ps1')

View File

@@ -0,0 +1 @@
论坛资料快照:包含 BBS、Snitz 当前数据库和已有 BBS 备份。manifest.json 记录大小、SHA-256、表数量与采集时间。恢复前备份现有数据库并暂停论坛写入;tar -xf forums.tar.xz 解压后按 restorePath 复制到 lxj 对应位置。jarod.asp 实际为 Access 数据库,恢复时保留原扩展名。

View File

@@ -0,0 +1,26 @@
[
{
"bytes": 1933312,
"capturedAt": "2026-11-27T10:22:35.1813697+08:00",
"sha256": "85CB84F3919F4D0980AF53A50CD01F21E37E9EFB8181CACC02F2408A9C06BF91",
"restorePath": "2002\\BBS\\DATA\\jarod.asp",
"tableCount": 26,
"file": "bbs-current.mdb"
},
{
"bytes": 3543040,
"capturedAt": "2026-11-27T10:22:35.4226098+08:00",
"sha256": "28BC6CE8716041791D7A3C00B363FE339FAA3CDECA3E92E310298BDF2FF41CD2",
"restorePath": "2002\\SNIZ\\TOOLS\\snitz2000.mdb",
"tableCount": 25,
"file": "sniz-current.mdb"
},
{
"bytes": 1916928,
"capturedAt": "2026-11-27T10:22:35.6201867+08:00",
"sha256": "D4983E9E3D28E0E3786188EBFB3A8212D4ED98A9D3A7D08F5C921FE51B2ABF64",
"restorePath": "2002\\BBS\\Databackup\\JAROD.ASP",
"tableCount": 26,
"file": "bbs-existing-backup.mdb"
}
]

View File

@@ -0,0 +1,8 @@
$ErrorActionPreference='Stop'
$root='C:\ProgramData\AcerWeeklyReport'
$action=New-ScheduledTaskAction -Execute 'C:\Python312\python.exe' -Argument ($root+'\report.py --send') -WorkingDirectory $root
$trigger=New-ScheduledTaskTrigger -Weekly -WeeksInterval 1 -DaysOfWeek Friday -At '19:00'
$settings=New-ScheduledTaskSettingsSet -StartWhenAvailable -WakeToRun -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 15) -ExecutionTimeLimit (New-TimeSpan -Hours 2)
Register-ScheduledTask -TaskName 'Acer Weekly Access Report' -Action $action -Trigger $trigger -Settings $settings -User SYSTEM -RunLevel Highest -Description 'Friday 19:00 China time: email seven-day IIS access analysis and verified 18:00 dual Git push outcome to aqlxj@qq.com using local WinWebMail.' -Force|Out-Null
Export-ScheduledTask -TaskName 'Acer Weekly Access Report' | Set-Content ($root+'\task-definition.xml') -Encoding Unicode
'Weekly report task installed.'

View File

@@ -0,0 +1,32 @@
# Acer 网站访问与代码备份周报
Acer 本机 Windows 计划任务 `Acer Weekly Access Report`,每周五北京时间19:00,以SYSTEM运行,无需Mac或Cindy在线。
收件人 aqlxj@qq.com,发件人 ght@aqsh3x.com,经本机 WinWebMail 发信。
正文为内联样式 HTML + 纯文本 MIME 双版本,不发送 Markdown 源码;粗体与符号突出重要结论,适合手机邮箱阅读。实际微信内显示效果受邮箱客户端支持影响。
统计截至计划执行时刻的7×24小时,对比前7天;延迟补跑仍采用最近一个周五19:00作为截止,避免统计窗口漂移。
涵盖全部 IIS 站点的访问量、域名、热门路径、爬虫自报身份、代理/客户端地址、状态码、5xx/404、常见探测与慢请求。
历史缺少Host的请求列为未知;只在代理来自本机回环地址时采用 CF-Connecting-IP,仍不把IP数当作人数。
每天日志按UTC转换北京时间,支持字段变更与IIS增强日志;不采集完整查询参数、Cookie、数据库内容或凭据。
读取18点同步状态与Windows任务信息,并只读查询两库master。旧成功、任务运行中、查询失败和提交不一致均不会当作本次成功。发现错误仅报告,不自动修改站点或强推。
本次预期时段的成功记录+两库提交相同才标记推送成功。
配置/脚本位于 C:\ProgramData\AcerWeeklyReport。
每次生成的HTML、TXT、JSON、EML和已发送标记在reports目录,状态status.json,日志logs;本机保留180天,不自动进入Git。
SMTP接受发送不等同于外部邮箱投递成功,必要时检查本机投递日志和退信。
同一周期已发送不重复发送;失败15分钟重试最多3次;错过后补跑并允许唤醒设备。
只生成预览:C:\Python312\python.exe C:\ProgramData\AcerWeeklyReport\report.py --test
发送即时测试:上述命令加 --send
启动正式任务:Start-ScheduledTask -TaskName 'Acer Weekly Access Report'
停用:Disable-ScheduledTask -TaskName 'Acer Weekly Access Report'
专用SMTP凭据读取现有 AcerBbsMail\smtp-auth.txt,不另存、不打印、不推送。
## 2026-11-27 阅读与内网分析修订
用户已收到首封测试邮件,要求更清晰的emoji标注、展示访问域名、重点分析内网IP访问和访问者IP。
新版采用emoji分节+粗体+单列信息卡,避免长路径及Git提交挤在窄表格中。
入口区分域名与服务器IP(包含端口),新字段已知记录优先展示,历史未知另列覆盖率。
访问者IP按内网、公网、本机代理/特殊地址分类;每IP列出请求占比、首末活跃、入口、常用页面、404/5xx、爬虫和慢请求/探测提示。
内网按IPv4 /24、IPv6 /64作分析归组,不推断真实子网掩码,不将地址当作具体人员。仅本机回环来源采用CF客户端字段,直接内网连接不采用自报头。

View File

@@ -0,0 +1,295 @@
"""Acer native weekly report; stdlib only; credentials never leave this machine."""
import argparse, collections as C, datetime as D, email.policy, hashlib, html, ipaddress, json, logging, os, pathlib as P, re, smtplib, subprocess, sys, traceback, urllib.parse, uuid
from email.message import EmailMessage
TZ=D.timezone(D.timedelta(hours=8)); ROOT=P.Path(r'C:\ProgramData\AcerWeeklyReport')
CONFIG=ROOT/'settings.json'; STATE=ROOT/'status.json'; GITROOT=P.Path(r'C:\ProgramData\AcerGitSync')
def load(p,default=None):
try:return json.loads(P.Path(p).read_text(encoding='utf-8-sig'))
except FileNotFoundError:return default
def save(p,obj):
p=P.Path(p);tmp=p.with_suffix(p.suffix+'.tmp');tmp.write_text(json.dumps(obj,ensure_ascii=False,indent=2),encoding='utf-8');tmp.replace(p)
def dt(s):return D.datetime.fromisoformat(s).astimezone(TZ)
def show(t):return t.strftime('%Y-%m-%d %H:%M:%S')
def pct(a,b):return f'{100*a/b:.1f}%' if b else '—'
def short(s,n=120):return str(s)[:n]
def ip_kind(value):
try:a=ipaddress.ip_address(value)
except ValueError:return '无法识别'
if a.is_loopback:return '本机回环 / 代理'
if a.is_link_local:return '链路本地地址'
nets=['10.0.0.0/8','172.16.0.0/12','192.168.0.0/16'] if a.version==4 else ['fc00::/7']
if any(a in ipaddress.ip_network(n) for n in nets):return '内网 IP'
return '公网 IP' if a.is_global else '保留 / 特殊地址'
def host_kind(host):
try:
try:a=ipaddress.ip_address(host);return ip_kind(str(a))
except ValueError:pass
name=urllib.parse.urlsplit('//'+host).hostname or ''
if name.lower()=='localhost':return '本机名称'
try:return ip_kind(str(ipaddress.ip_address(name)))
except ValueError:return '域名入口' if name else '未知入口'
except ValueError:return '未知入口'
def botname(ua):
for x in ['ClaudeBot','meta-externalagent','meta-webindexer','Applebot','Googlebot','Bingbot','YisouSpider','Bytespider','GPTBot','Amazonbot','AhrefsBot','SemrushBot']:
if x.lower() in ua.lower():return x
return '其他爬虫标识' if re.search('bot|spider|crawler',ua,re.I) else None
class Stats:
def __init__(self,track_clients=False):
self.track_clients=track_clients;self.clients={};self.origin=C.Counter();self.peers=C.Counter()
self.n=0;self.ms=C.Counter();self.status=C.Counter();self.paths=C.Counter();self.bots=C.Counter();self.sources=C.Counter();self.errors=C.Counter();self.missing=C.Counter();self.slow=C.Counter();self.methods=C.Counter();self.error_codes=C.Counter();self.probes=C.Counter();self.first=None;self.last=None;self.real=0;self.hosts=C.Counter();self.unknown=0
def add(self,t,d):
self.n+=1;sc=int(d['sc-status']);ms=max(0,int(d.get('time-taken','0')));path=d['cs-uri-stem'];ua=d.get('cs(User-Agent)','');peer=d.get('c-ip','-')
self.status[sc]+=1;self.ms[ms]+=1;self.paths[path]+=1;self.methods[d.get('cs-method','-')]+=1
self.first=min(self.first or t,t);self.last=max(self.last or t,t)
host=d.get('cs-host',d.get('cs(Host)','-'))
if host in ('','-'):self.unknown+=1
else:self.hosts[short(host.lower(),150)]+=1
source=peer;cf=d.get('CF-Connecting-IP',d.get('cs(CF-Connecting-IP)','-'))
# Only loopback is a trusted proxy peer; never trust arbitrary remote CF headers.
if peer in ('::1','127.0.0.1') and cf not in ('-',''):
try:source=str(ipaddress.ip_address(cf));self.real+=1
except ValueError:pass
self.sources[source]+=1
if self.track_clients:
profile=self.clients.setdefault(source,Stats())
profile.add(t,d);profile.origin['本机代理提供的客户端IP' if source!=peer else '日志连接地址']+=1;profile.peers[peer]+=1
bot=botname(ua)
if bot:self.bots[bot]+=1
if sc>=500:
self.errors[(path,sc,d.get('sc-substatus','0'))]+=1
for code in set(re.findall(r'(?i)\b(?:800[a-f0-9]{5}|ASP_[0-9]+)\b',d.get('cs-uri-query',''))):self.error_codes[code.lower()]+=1
if sc==404:self.missing[path]+=1
if ms>3000:self.slow[path]+=1
if re.search(r'(?i)(/\.env(?:/|$)|/\.git(?:/|$)|webshell|/shell(?:\.|/|$)|/wp-|phpmyadmin|Telerik\.Web\.UI)',path):self.probes[(path,sc)]+=1
def summary(self):
rank=max(1,int(self.n*.95+.999999));acc=0;p95=0
for ms,n in sorted(self.ms.items()):
acc+=n
if acc>=rank:p95=ms;break
return dict(requests=self.n,status=dict(self.status),average_ms=round(sum(ms*n for ms,n in self.ms.items())/self.n,1) if self.n else 0,p95_ms=p95,slow3s=sum(self.slow.values()),bot_claims=sum(self.bots.values()),host_known=self.n-self.unknown,real_ip_header_requests=self.real)
def collect(start,end,config):
total=Stats(track_clients=True);previous=Stats();daily={};sites={};hosts={};modules={};bad=0;files=0;unread=[]
earliest=start-D.timedelta(days=7)
for p in sorted(P.Path(config['log_root']).glob('W3SVC*/*.log')):
match=re.match(r'u_ex(\d{6})',p.name)
if match:
try:fd=D.datetime.strptime(match[1],'%y%m%d').date()
except ValueError:continue
if not (earliest.astimezone(D.timezone.utc).date()<=fd<=end.astimezone(D.timezone.utc).date()):continue
fields=[]
try:
with p.open(encoding='utf-8-sig',errors='replace') as f:
files+=1
for line in f:
if line.startswith('#Fields:'):fields=line.strip().split()[1:];continue
if line.startswith('#') or not fields:continue
values=line.strip().split()
if len(values)!=len(fields):bad+=1;continue
d=dict(zip(fields,values))
try:t=D.datetime.fromisoformat(d['date']+'T'+d['time']).replace(tzinfo=D.timezone.utc).astimezone(TZ)
except (ValueError,KeyError):bad+=1;continue
if not earliest<=t<end:continue
try:int(d['sc-status']);int(d.get('time-taken','0'))
except (KeyError,ValueError):bad+=1;continue
if t<start:previous.add(t,d);continue
total.add(t,d);day=t.strftime('%m-%d');daily.setdefault(day,Stats()).add(t,d)
site=p.parent.name;sites.setdefault(site,Stats()).add(t,d)
host=d.get('cs-host',d.get('cs(Host)','-'));hosts.setdefault(short(host,150),Stats()).add(t,d)
path=d['cs-uri-stem'].lower()
module='Snitz 旧论坛' if path.startswith('/lxj/2002/sniz') else 'BBS 校园乐园' if path.startswith('/lxj/2002/bbs') else '监控与采集接口' if path.startswith(('/system_monitor','/acer-metrics')) else 'LXJ 工作主页及其他资源' if path.startswith('/lxj') else '主门户及其他资源'
modules.setdefault(module,Stats()).add(t,d)
except OSError as e:unread.append(p.name+': '+type(e).__name__)
return total,previous,daily,sites,hosts,modules,dict(files=files,malformed=bad,unreadable=unread)
def native_context():
ps="""$r=@{};foreach($n in @('Acer Anqing Weekly Git Sync','Acer Weekly Access Report')){try{$t=Get-ScheduledTask -TaskName $n -ErrorAction Stop;$i=Get-ScheduledTaskInfo -TaskName $n;$r[$n]=@{state=[string]$t.State;result=$i.LastTaskResult;last=$i.LastRunTime.ToString('o');next=$i.NextRunTime.ToString('o')}}catch{$r[$n]=@{error='Task not found'}}};$r.sites=@(Import-Module WebAdministration;Get-Website|ForEach-Object {@{id=$_.id;name=$_.name}});$r|ConvertTo-Json -Depth 5 -Compress"""
r=subprocess.run(['powershell.exe','-NoProfile','-Command',ps],capture_output=True,timeout=45)
if r.returncode:raise RuntimeError('Cannot inspect native scheduled tasks')
return json.loads(r.stdout.decode('utf-8-sig',errors='replace'))
def git_check(end):
state=load(GITROOT/'status.json',{}) or {};c=load(GITROOT/'settings.json',{}) or {};out=dict(state=state,remotes={})
env=os.environ.copy();env.update(GIT_SSH_COMMAND='D:/Git/usr/bin/ssh.exe -F C:/ProgramData/AcerGitSync/ssh_config -o ServerAliveInterval=10 -o ServerAliveCountMax=2',GIT_SSH_VARIANT='ssh',GIT_TERMINAL_PROMPT='0')
for key in ['github','intranet']:
try:
r=subprocess.run([r'D:\Git\cmd\git.exe','ls-remote',c[key],'refs/heads/master'],env=env,capture_output=True,timeout=70)
head=r.stdout.decode('ascii',errors='replace').split()
out['remotes'][key]=dict(ok=r.returncode==0 and bool(head),head=head[0] if head else None)
except (OSError,KeyError,subprocess.TimeoutExpired):out['remotes'][key]=dict(ok=False,head=None)
# Expected most recent Friday 18:00, even when a missed report catches up on Saturday.
expected=end.replace(hour=18,minute=0,second=0,microsecond=0)-D.timedelta(days=(end.weekday()-4)%7)
if expected>end:expected-=D.timedelta(days=7)
try:fresh=expected<=dt(state['startedAt'])<=end
except (KeyError,ValueError):fresh=False
out['expected_run']=show(expected);out['fresh']=fresh
out['verified']=bool(fresh and state.get('success') and state.get('githubPushed') and state.get('intranetPushed') and all(x['ok'] and x['head']==state.get('commit') for x in out['remotes'].values()))
return out
class Report:
def __init__(self):self.parts=[];self.text=[]
def title(self,s):self.parts.append('<h2 style="font-size:20px;line-height:1.5;margin:28px 0 12px;padding-top:16px;border-top:2px solid #d8e3ed"><strong>'+html.escape(s)+'</strong></h2>');self.text.append('\n━━━━━━━━━━━━━━━━\n'+s)
def card(self,title,items):
self.parts.append('<div style="margin:12px 0;padding:14px;border:1px solid #d8e3ed;border-radius:8px;background:#f7f9fc"><p style="margin:0 0 8px;font-size:17px;overflow-wrap:anywhere;word-break:break-all"><strong>'+html.escape(title)+'</strong></p>'+''.join('<p style="margin:5px 0;overflow-wrap:anywhere;word-break:break-all"><strong>'+html.escape(str(k))+':</strong>'+html.escape(str(v))+'</p>' for k,v in items)+'</div>')
self.text.append('\n'+title);self.text.extend(str(k)+':'+str(v) for k,v in items)
def line(self,s,bold=False):self.parts.append('<p style="margin:9px 0;overflow-wrap:anywhere">'+('<strong>'+html.escape(s)+'</strong>' if bold else html.escape(s))+'</p>');self.text.append(s)
def table(self,headers,rows):
rows=list(rows)
if not rows:self.line('本时段没有相关记录。');return
# Vertical items remain readable in QQ Mail / WeChat narrow message columns.
if len(headers)==2:
for row in rows:
self.parts.append('<div style="padding:8px 0;border-bottom:1px solid #e5e9ee;overflow-wrap:anywhere;word-break:break-all">'+html.escape(str(row[0]))+'<br><strong>'+html.escape(str(headers[1]))+':'+html.escape(str(row[1]))+'</strong></div>')
self.text.append(str(row[0])+' | '+str(headers[1])+':'+str(row[1]))
return
for row in rows:self.card(str(row[0]),list(zip(headers[1:],row[1:])))
def finish(self):return '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="margin:0;padding:16px;font-family:Arial,Microsoft YaHei,sans-serif;font-size:16px;line-height:1.7;color:#222;background:#fff"><div style="max-width:720px;margin:auto">'+''.join(self.parts)+'</div></body></html>','\n'.join(self.text)+'\n'
def build(start,end,c,test=False):
total,prev,daily,sites,hosts,modules,quality=collect(start,end,c);summary=total.summary();ps=prev.summary();context=native_context();git=git_check(end)
def device_title(value):
try:
try:address=str(ipaddress.ip_address(value))
except ValueError:address=urllib.parse.urlsplit('//'+value).hostname
except ValueError:address=value
name=c.get('device_names',{}).get(address)
return value+(' · '+name if name else '')
r=Report();r.title(('【测试】' if test else '')+'📬 Acer 网站访问与代码备份周报');r.line('统计区间:'+show(start)+' 至 '+show(end)+'(北京时间,截止时刻不含在内)');r.line('生成时间:'+show(D.datetime.now(TZ)))
r.title('📌 一眼看懂本周情况')
r.line(f"📈 总请求 {total.n:,} 次;自报爬虫占 {pct(summary['bot_claims'],total.n)};500 类错误 {sum(n for k,n in total.status.items() if k>=500):,} 次。",True)
r.line(('✅ 18:00 双仓库推送已成功,且远端提交核对一致。' if git['verified'] else '⚠️ 18:00 推送尚未确认成功:请看下方实际任务与两库结果。'),True)
if summary['bot_claims']>total.n*.5:r.line('🤖 自动抓取占主要流量,不能将请求量视为真人访问人数。',True)
if total.slow:r.line('🐢 超过 3 秒的请求最集中在:'+total.slow.most_common(1)[0][0],True)
r.title('📊 访问总览与上周对比')
def change(a,b):return f'{(a-b)*100/b:+.1f}%' if b else '上期为0,无法计算增幅'
r.table(['指标','本周','上一个7天'],[['请求数',f'{total.n:,}',f'{prev.n:,}'],['平均耗时',str(summary['average_ms'])+' ms',str(ps['average_ms'])+' ms'],['95%请求耗时',str(summary['p95_ms'])+' ms',str(ps['p95_ms'])+' ms'],['超过3秒',summary['slow3s'],ps['slow3s']],['5xx错误',sum(n for k,n in total.status.items() if k>=500),sum(n for k,n in prev.status.items() if k>=500)]])
r.line('请求量较上期变化:'+change(total.n,prev.n)+'。请求包含页面、图片、脚本、接口和爬虫,不等同于页面浏览量或人数。')
r.table(['日期','请求','5xx / 慢请求'],[(d,f'{s.n:,}',f"{sum(n for k,n in s.status.items() if k>=500)} / {sum(s.slow.values())}") for d,s in sorted(daily.items())])
r.line('周报按连续7×24小时统计,首尾日期为部分时段。')
r.title('🌐 访问入口:域名与服务器 IP')
known=[(h,st) for h,st in hosts.items() if h not in ('-','')]
domains=[(h,st) for h,st in known if host_kind(h) in ('域名入口','本机名称')]
iphosts=[(h,st) for h,st in known if host_kind(h) not in ('域名入口','本机名称')]
r.line('这里回答“访问者在地址栏输入了哪个域名或服务器 IP”;下一节的访问者 IP 回答“请求从哪里来”。',True)
r.line('🏫 通过内网 / 公网 IP 直接访问',True)
for h,st in sorted(iphosts,key=lambda x:x[1].n,reverse=True)[:10]:
r.card('🖥️ '+device_title(h),[('入口类型',host_kind(h)),('请求量',f'{st.n:,} 次'),('连接 / 客户端地址', ';'.join(f'{ip}({n}次)' for ip,n in st.sources.most_common(4))),('常用页面',';'.join(f'{path}({n}次)' for path,n in st.paths.most_common(3)))])
if not iphosts:r.line('📭 已记录 Host 的请求中,暂无 IP 直访记录;这不代表过去没有内网访问。')
r.line('🔗 通过域名访问',True)
for h,st in sorted(domains,key=lambda x:x[1].n,reverse=True)[:10]:
r.card('🌐 '+h,[('请求量',f'{st.n:,} 次'),('自报爬虫',pct(sum(st.bots.values()),st.n)),('5xx错误',sum(n for code,n in st.status.items() if code>=500)),('常用页面',';'.join(f'{path}({n}次)' for path,n in st.paths.most_common(2)))])
if not domains:r.line('📭 已记录 Host 的请求中暂无域名访问;不会把 Referer 来源页冒充实际入口。')
r.line(f"🕰️ 历史入口未知:{total.unknown:,} 次;入口记录覆盖 {total.n-total.unknown:,}/{total.n:,} 次({pct(total.n-total.unknown,total.n)})。",True)
r.line('新字段从2026年11月27日启用。旧日志缺少 Host,只能分析当时的连接 IP,不能反推出访问域名。已知入口单独列出,不会被大量旧的“未知”记录淹没。')
site_names={'W3SVC'+str(s['id']):s['name'] for s in context.get('sites',[])}
r.table(['IIS站点','请求数','5xx'],[(site_names.get(k,k),s.n,sum(n for code,n in s.status.items() if code>=500)) for k,s in sites.items()])
r.title('🏫 热门页面与工作区')
r.table(['区域','请求数','95%耗时'],[(k,s.n,str(s.summary()['p95_ms'])+' ms') for k,s in sorted(modules.items(),key=lambda x:x[1].n,reverse=True)])
r.table(['热门路径(不含查询参数)','请求数'],total.paths.most_common(10))
r.title('🤖 爬虫抓取情况')
r.table(['自报爬虫名称','请求数'],total.bots.most_common(10))
r.line('爬虫名称来自 User-Agent,自报身份未经真实性验证;无爬虫标识也不保证是真人。')
r.title('👥 访问者 IP:内网设备与代理分开看')
categories=C.Counter();groups={};nets=C.Counter()
for ip,profile in total.clients.items():
kind=ip_kind(ip);categories[kind]+=profile.n;groups.setdefault(kind,[]).append((ip,profile))
try:
addr=ipaddress.ip_address(ip)
if kind=='内网 IP':nets[str(ipaddress.ip_network(str(addr)+('/24' if addr.version==4 else '/64'),strict=False))]+=profile.n
except ValueError:pass
r.table(['地址类型','请求数'],categories.most_common())
if c.get('device_names'):r.line('🏷️ 固定设备名称来自学校提供的内网分配表('+c.get('device_names_as_of','日期未记录')+'),设备名称不等于实际操作人员身份。')
r.line('📌 以下是地址与活动统计,不是实名身份或真实人数。内网地址可能是个人设备、共享出口或反向代理;不会仅凭 IP 把它认定为某个人。')
def client_cards(entries,limit):
for ip,profile in sorted(entries,key=lambda x:x[1].n,reverse=True)[:limit]:
q=profile.summary();probes=sum(profile.probes.values());bc=sum(profile.bots.values())
signals=[]
if probes:signals.append(f'⚠️ 常见漏洞路径探测 {probes} 次')
if bc:signals.append('🤖 自报爬虫 '+pct(bc,profile.n))
if q['slow3s']:signals.append(f"🐢 慢请求 {q['slow3s']} 次")
if ip_kind(ip)=='本机回环 / 代理':signals.append('🔒 只看到本机连接,不能识别后面的访问者')
first=show(profile.first);last=show(profile.last)
r.card('👤 '+device_title(ip),[('地址性质',ip_kind(ip)),('请求 / 占比',f'{profile.n:,} 次 / '+pct(profile.n,total.n)),('地址依据',';'.join(profile.origin)),('活跃时段',first+' 至 '+last),('访问入口',';'.join(f'{h}({n}次)' for h,n in profile.hosts.most_common(3)) or '旧日志未记录'),('常用页面',';'.join(f'{path}({n}次)' for path,n in profile.paths.most_common(3))),('错误情况',f"404:{profile.status[404]} 次;5xx:{sum(n for code,n in profile.status.items() if code>=500)} 次"),('行为提示',';'.join(signals) or '未触发本报告的探测 / 慢请求规则;不等于已证实为真人')])
r.line('🏫 内网地址活动(按请求量排列,最多12个)',True)
client_cards(groups.get('内网 IP',[]),12)
if not groups.get('内网 IP'):r.line('本时段未记录到内网来源地址。')
if nets:
r.line('🧩 内网地址段汇总(IPv4按/24、IPv6按/64归组,不代表实际网络掩码)',True)
r.table(['地址段','请求数'],nets.most_common(8))
others=[pair for kind,entries in groups.items() if kind!='内网 IP' for pair in entries]
r.line('🌍 公网 / 本机代理 / 其他地址(最多8个)',True);client_cards(others,8)
r.line(f"🔎 经本机代理提供客户端 IP 的请求 {total.real:,} 次。未得到客户端字段的回环请求单独标注;直接连接的内网 IP 原样统计。公网 IP 不查询地理位置,不凭地址推断人员身份。")
r.title('🚨 错误与异常探测')
r.table(['HTTP状态','请求数','占比'],[(sc,n,pct(n,total.n)) for sc,n in sorted(total.status.items())])
r.table(['5xx路径','状态 / 子状态','次数'],[(p,f'{sc}/{sub}',n) for (p,sc,sub),n in total.errors.most_common(10)])
r.table(['ASP/数据库错误代码','次数'],total.error_codes.most_common(6))
r.table(['404路径','次数'],total.missing.most_common(8))
r.table(['常见漏洞路径探测','响应码','次数'],[(p,sc,n) for (p,sc),n in total.probes.most_common(8)])
r.line('探测请求不等同于入侵成功;HTTP 200 也不能单独证明成功,需要结合内容与应用记录核对。')
r.title('🐢 响应速度与改进建议')
r.table(['超过3秒的路径','次数'],total.slow.most_common(8))
if total.errors:r.line('🛠️ 优先核对高频5xx页面,按日志中的错误码排查;数据库锁冲突需结合应用代码和并发情况确认。',True)
if total.bots and summary['bot_claims']>total.n*.5:r.line('🛠️ 优先约束会员排序、无限日历和操作页的重复抓取;robots.txt 用于声明抓取规则,实际限速需由服务器或入口规则执行。',True)
if total.unknown:r.line('🕰️ 早期日志缺少域名,真实来源统计也不完整;本报告明确列出覆盖率,后续日志补齐后再评估。')
if total.missing:r.line('🔗 核对热门404是否为站内旧链接;不要将扫描器访问的不存在路径误当作需要新增的页面。')
r.title('📦 18:00 双仓库备份结果')
state=git['state'];task=context.get('Acer Anqing Weekly Git Sync',{})
r.line('应核对的计划执行时刻:'+git['expected_run'])
r.line('Windows任务状态:'+str(task.get('state','未知'))+';上次结果码:'+str(task.get('result','未知'))+';下次计划:'+str(task.get('next','未知')))
r.line('同步脚本记录:开始 '+str(state.get('startedAt','无'))+';完成 '+str(state.get('finishedAt','尚未完成')))
r.line('处理阶段:'+str(state.get('phase','无记录'))+';本次预期时段记录:'+('是' if git['fresh'] else '否(旧记录不能当作本次成功)'),True)
if state.get('error'):r.line('失败信息:'+short(state['error'],250),True)
head=state.get('commit');r.line('本机同步提交:'+str(head or '暂无'))
r.table(['目标仓库','推送/核验状态','当前远端提交'],[(label,('已核对一致' if git['fresh'] and state.get('success') and x['ok'] and x['head']==head else '与脚本记录一致,但不是本次时段' if x['ok'] and head and x['head']==head else '需要检查' if x['ok'] else '远端查询失败'),x['head'] or '未知') for key,label in [('github','GitHub 私有库'),('intranet','内网 Gitea')] for x in [git['remotes'][key]]])
r.line('GitHub:https://github.com/jarodlee/anqing;内网:http://192.168.1.99:3000/jarod/anqing')
r.line('核验为只读查询,不会补推或强制覆盖。若18点任务仍在运行,本邮件会明确报告“未确认完成”,不会把昨天的成功当作今天的结果。')
r.title('📝 数据范围与完整性')
r.line(f"读取日志文件 {quality['files']} 个;格式不完整行 {quality['malformed']} 行;读取失败 {len(quality['unreadable'])} 个。")
r.line('本期最早/最新已落盘请求:'+(show(total.first)+' / '+show(total.last) if total.first else '没有日志记录'))
r.line('IIS 存在写盘延迟,截止前尚未落盘的请求可能未计入;本报告不强制刷新或重启网站。')
if quality['unreadable']:r.line('未能读取:'+', '.join(quality['unreadable']),True)
r.line('由 Acer 本机自动生成并发送。邮件包含 HTML 与纯文本双版本;不包含密码、Cookie、完整查询参数或数据库内容。')
markup,plain=r.finish()
data=dict(start=start.isoformat(),end=end.isoformat(),summary=summary,previous=ps,quality=quality,git=git)
return markup,plain,data
def send(c,subject,markup,plain):
credential=P.Path(c['credential_file']).read_text(encoding='utf-16').splitlines()
if len(credential)<2:raise RuntimeError('SMTP credential file format invalid')
msg=EmailMessage(policy=email.policy.SMTP);msg['From']=c['sender'];msg['To']=c['recipient'];msg['Subject']=subject;msg['Date']=D.datetime.now(TZ);msg['Message-ID']=f'<acer-weekly-{uuid.uuid4().hex}@aqsh3x.com>'
msg.set_content(plain);msg.add_alternative(markup,subtype='html')
# Existing local WinWebMail; authentication never crosses this machine.
with smtplib.SMTP(c['smtp_host'],c['smtp_port'],timeout=45) as smtp:
smtp.ehlo();smtp.login(credential[0],credential[1]);refused=smtp.send_message(msg)
if refused:raise RuntimeError('SMTP recipient rejected')
return str(msg['Message-ID']),msg.as_bytes()
def main():
parser=argparse.ArgumentParser();parser.add_argument('--send',action='store_true');parser.add_argument('--test',action='store_true');args=parser.parse_args()
ROOT.mkdir(parents=True,exist_ok=True);(ROOT/'reports').mkdir(exist_ok=True);(ROOT/'logs').mkdir(exist_ok=True)
now=D.datetime.now(TZ);logging.basicConfig(filename=ROOT/'logs'/('report-'+now.strftime('%Y%m%d')+'.log'),level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s',encoding='utf-8')
c=load(CONFIG);end=now.replace(microsecond=0) if args.test else now.replace(hour=19,minute=0,second=0,microsecond=0)-D.timedelta(days=(now.weekday()-4)%7)
if end>now:end-=D.timedelta(days=7)
key=end.strftime('%Y%m%d-%H%M%S')+('-test' if args.test else '-weekly');marker=ROOT/'reports'/(key+'.sent.json')
if args.send and marker.exists():logging.info('Report already sent: %s',key);print('Already sent; skipped');return
state=dict(startedAt=now.isoformat(),success=False,phase='Generating',test=args.test,periodEnd=end.isoformat(),recipient=c['recipient']);save(STATE,state)
try:
markup,plain,data=build(end-D.timedelta(days=7),end,c,args.test)
prefix=ROOT/'reports'/key;prefix.with_suffix('.html').write_text(markup,encoding='utf-8');prefix.with_suffix('.txt').write_text(plain,encoding='utf-8');save(prefix.with_suffix('.json'),data)
state['report']=str(prefix.with_suffix('.html'));state['phase']='Generated'
if args.send:
state['phase']='Sending';save(STATE,state)
subject=('【测试】' if args.test else '')+'📬 Acer 周报|网站访问与18点代码推送|'+end.strftime('%Y-%m-%d')
message_id,raw=send(c,subject,markup,plain)
save(marker,dict(sentAt=D.datetime.now(TZ).isoformat(),recipient=c['recipient'],messageId=message_id));prefix.with_suffix('.eml').write_bytes(raw)
state.update(phase='Accepted by local WinWebMail SMTP',messageId=message_id)
state.update(success=True,finishedAt=D.datetime.now(TZ).isoformat());save(STATE,state);logging.info('Completed %s send=%s',key,args.send);print(json.dumps(state,ensure_ascii=True))
# Reports may contain IPs; retain locally 180 days, never add generated reports to Git.
for folder in [ROOT/'reports',ROOT/'logs']:
for p in folder.iterdir():
if p.is_file() and p.stat().st_mtime<now.timestamp()-180*86400:p.unlink()
except Exception as e:
# Avoid SMTP exception strings that could echo authentication data.
state.update(phase='Failed',error=type(e).__name__,finishedAt=D.datetime.now(TZ).isoformat());save(STATE,state);logging.error('Failed: %s',type(e).__name__);print(json.dumps(state));raise SystemExit(1)
if __name__=='__main__':main()

View File

@@ -0,0 +1,16 @@
{
"recipient": "aqlxj@qq.com",
"sender": "ght@aqsh3x.com",
"smtp_host": "127.0.0.1",
"smtp_port": 25,
"credential_file": "C:\\ProgramData\\AcerBbsMail\\smtp-auth.txt",
"log_root": "C:\\inetpub\\logs\\LogFiles",
"device_names": {
"192.168.110.5": "Kali服务器",
"192.168.110.99": "M4 mini控制台",
"192.168.110.8": "总务处电脑",
"192.168.1.99": "GPD小主机",
"192.168.1.6": "Acer打印电脑"
},
"device_names_as_of": "2026-11-27"
}