Files
kefu/im/server-fix-20260831/diagnose_panel_network.py
2026-09-03 08:38:17 +08:00

25 lines
1.7 KiB
Python

import os,subprocess,time,json,collections
result={}
for p in ['/proc/sys/net/netfilter/nf_conntrack_count','/proc/sys/net/netfilter/nf_conntrack_max']:
if os.path.exists(p):result[p.rsplit('/',1)[-1]]=open(p).read().strip()
for name,args in [('socket_summary',['ss','-s']),('panel_process',['ps','-p','737470,737482','-o','pid,ppid,lstart,etime,%cpu,%mem,rss,comm']),('routes',['ip','route']),('queue',['tc','-s','qdisc','show'])]:
try:result[name]=subprocess.check_output(args,stderr=subprocess.STDOUT,universal_newlines=True,timeout=4)[:1800]
except Exception as e:result[name]=type(e).__name__
def network():
d={}
for l in open('/proc/net/dev'):
if ':' in l:
name,fields=l.split(':',1);v=list(map(int,fields.split()));d[name.strip()]=v
return d
start=network();t=time.monotonic();time.sleep(3);end=network();dt=time.monotonic()-t
result['network_per_second']={k:{'rx_Mbps':round((v[0]-start[k][0])*8/dt/1e6,3),'tx_Mbps':round((v[8]-start[k][8])*8/dt/1e6,3),'rx_drop_delta':v[3]-start[k][3],'tx_drop_delta':v[11]-start[k][11]} for k,v in end.items() if k!='lo'}
try:
p=subprocess.run(['dmesg','--ctime'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True,timeout=4)
result['kernel_recent_resource_messages']=[l for l in p.stdout.splitlines()[-500:] if any(x in l.lower() for x in ['conntrack','out of memory','oom-kill','blocked for','net_ratelimit'])][-8:]
except Exception:pass
try:
p=subprocess.run(['iptables','-S'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True,timeout=4)
result['firewall_relevant_rules']=[l for l in p.stdout.splitlines() if '8686' in l or l.startswith('-P') or ('-j DROP' in l and '--dport' not in l)][:15]
except Exception:pass
print(json.dumps(result),flush=True)