本文目录导读:

结束异常进程的方法有多种,具体取决于你的操作系统和需求,以下是几种常见场景的脚本方案:
Windows (PowerShell)
按进程名结束
# 结束所有notepad.exe进程 Stop-Process -Name "notepad" -Force # 如果进程不存在,不报错 Stop-Process -Name "notepad" -Force -ErrorAction SilentlyContinue
按CPU或内存使用率结束
# 结束CPU使用率超过80%的进程
Get-Process | Where-Object { $_.CPU -gt 80 } | Stop-Process -Force
# 结束内存使用超过500MB的进程
Get-Process | Where-Object { $_.WorkingSet -gt 500MB } | Stop-Process -Force
按运行时间结束
# 结束运行超过24小时的进程
Get-Process | Where-Object {
$_.StartTime -and (Get-Date) - $_.StartTime -gt [TimeSpan]::FromHours(24)
} | Stop-Process -Force
Linux/macOS (Bash)
按进程名结束
# 结束所有名为"chrome"的进程 pkill chrome # 更精确的匹配 pkill -f "chrome.*--headless" # 匹配命令行中包含的模式
按资源使用率结束
#!/bin/bash
# 结束CPU使用超过90%的进程(排除空闲进程)
ps aux --sort=-%cpu | awk 'NR>1 && $3>90 {print $2}' | xargs -r kill -9
# 结束内存使用超过1GB的进程
ps aux --sort=-%mem | awk 'NR>1 && $6>1048576 {print $2}' | xargs -r kill -9
智能结束脚本
#!/bin/bash
# 综合检查:CPU>80% 或 内存>2GB 且运行超过1小时
ps -eo pid,pcpu,pmem,etime,comm --no-headers | while read pid cpu mem time cmd; do
# 转换etime为秒(简化处理)
if [[ $time == *-* ]]; then
days=${time%-*}
time=${time#*-}
fi
IFS=':' read -r h m s <<< "$time"
seconds=$((10#${h:-0}*3600 + 10#${m:-0}*60 + 10#${s:-0} + ${days:-0}*86400))
# 条件判断
if (( $(echo "$cpu > 80" | bc -l) )) || \
(( $(echo "$mem > 2.0" | bc -l) && $seconds > 3600 )); then
kill -9 $pid 2>/dev/null && echo "Killed: $cmd (PID: $pid)"
fi
done
Python (跨平台)
import psutil
import os
import time
def kill_abnormal_processes():
"""结束异常进程"""
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info', 'create_time']):
try:
# 条件1:CPU使用率超过80%
if proc.info['cpu_percent'] > 80:
proc.kill()
print(f"Killed {proc.info['name']} (CPU: {proc.info['cpu_percent']}%)")
continue
# 条件2:内存使用超过500MB
mem_mb = proc.info['memory_info'].rss / (1024 * 1024)
if mem_mb > 500:
proc.kill()
print(f"Killed {proc.info['name']} (Memory: {mem_mb:.1f}MB)")
continue
# 条件3:运行超过24小时
if proc.info['create_time']:
runtime = time.time() - proc.info['create_time']
if runtime > 86400: # 24小时
proc.kill()
print(f"Killed {proc.info['name']} (Runtime: {runtime/3600:.1f}h)")
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
if __name__ == "__main__":
kill_abnormal_processes()
Windows批处理 (CMD)
@echo off
:: 结束notepad进程
taskkill /f /im notepad.exe
:: 按内存使用排序结束(粗略)
for /f "skip=3 tokens=1" %%a in ('tasklist /fi "memusage gt 500000"') do (
taskkill /f /im %%a
)
综合监控脚本 (Linux/Windows)
# advanced_monitor.py
import psutil
import logging
from datetime import datetime
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def monitor_and_kill():
thresholds = {
'cpu_percent': 90, # CPU > 90%
'memory_mb': 1024, # 内存 > 1GB
'runtime_hours': 48, # 运行 > 48小时
'network_connections': 100 # 网络连接 > 100个
}
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info', 'create_time']):
try:
# 获取进程信息
pid = proc.info['pid']
name = proc.info['name']
cpu = proc.info['cpu_percent'] or 0
mem = proc.info['memory_info'].rss / (1024 * 1024)
# 获取运行时间
create_time = proc.info['create_time']
runtime = (datetime.now() - datetime.fromtimestamp(create_time)).total_seconds() / 3600 if create_time else 0
# 获取网络连接数
conn_count = len(proc.connections())
# 检查条件
reasons = []
if cpu > thresholds['cpu_percent']:
reasons.append(f"CPU={cpu:.1f}%")
if mem > thresholds['memory_mb']:
reasons.append(f"Memory={mem:.1f}MB")
if runtime > thresholds['runtime_hours']:
reasons.append(f"Runtime={runtime:.1f}h")
if conn_count > thresholds['network_connections']:
reasons.append(f"Connections={conn_count}")
if reasons:
proc.kill()
logging.warning(f"Killed {name} (PID: {pid}) - Reasons: {', '.join(reasons)}")
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
if __name__ == "__main__":
# 每5分钟执行一次
while True:
monitor_and_kill()
time.sleep(300)
注意事项
- 权限问题:结束系统进程可能需要管理员/root权限
- 误杀风险:建议先记录日志,设置白名单
- 信号选择:优先使用SIGTERM(15),失败再用SIGKILL(9)
- 谨慎使用:
kill -9可能造成数据丢失或文件损坏
你可以根据具体场景选择合适的方法,如果需要针对特定异常模式(如僵尸进程、CPU峰值等),我可以提供更精准的解决方案。