后台抓top 命令到文件内

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 功能:持续记录 top 命令输出到日志文件

# --- 配置项 ---
LOG_DIR="/data" # 日志目录
INTERVAL=3 # 刷新间隔(秒)
DURATION=0 # 运行总时长(秒),0=无限运行


# --- 初始化 ---
LOG_FILE="$LOG_DIR/top_$(date +%Y%m%d_%H%M%S).log" # 带时间戳的日志文件名
#mkdir -p "$LOG_DIR" # 创建目录

# --- 权限检查 ---
if [ ! -w "$LOG_DIR" ]; then
echo "错误:无法写入目录 $LOG_DIR,请检查权限!"
exit 1
fi

# --- 主逻辑 ---
echo "开始记录系统状态,日志文件: $LOG_FILE"
if [ "$DURATION" -gt 0 ]; then
timeout "$DURATION" top -b -d "$INTERVAL" >> "$LOG_FILE"&
else
echo "topstart"
top -b -d "$INTERVAL" >> "$LOG_FILE" &
fi

echo "hunanstart!!"






从文件内读取计算cpu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
```bash
#!/bin/bash

# 第一次采样
read -r cpu user nice system idle iowait irq softirq steal rest < <(grep '^cpu ' /proc/stat)
total1=$((user + nice + system + idle + iowait + irq + softirq + steal))
idle1=$((idle + iowait))

# 间隔 1 秒
sleep 1

# 第二次采样
read -r cpu user nice system idle iowait irq softirq steal rest < <(grep '^cpu ' /proc/stat)
total2=$((user + nice + system + idle + iowait + irq + softirq + steal))
idle2=$((idle + iowait))

# 计算差值
total_diff=$((total2 - total1))
idle_diff=$((idle2 - idle1))

# 计算使用率
cpu_usage=$(echo "scale=2; (100 * ($total_diff - $idle_diff) / $total_diff)" | bc)
echo "CPU 使用率: ${cpu_usage}%"

```