Bash 脚本示例,用于每隔 30 秒采集 CPU、内存和磁盘 I/O 信息,并支持 start 和 stop 操作

#!/bin/bash

# 设置日志文件
log_file="system_monitor.log"

# 检查参数
if [ "$1" != "start" ] && [ "$1" != "stop" ]; then
    echo "Usage: $0 [start|stop]"
    exit 1
fi

# 检查脚本是否已经在运行
if [ "$1" == "start" ] && [ -f /tmp/sys_monitor.pid ]; then
    echo "The monitoring script is already running. Use '$0 stop' to stop it."
    exit 1
fi

# 启动监控
if [ "$1" == "start" ]; then
    echo "Starting system monitoring..."
    echo "Monitoring started at $(date)" >> "$log_file"
    while true; do
        echo "----- $(date) -----"
        # 采集 CPU 使用情况
        top -n 1 | grep "Cpu(s)" | awk '{print "CPU Usage: " $2 "%"}'
        # 采集内存使用情况
        free -h | grep "Mem" | awk '{print "Memory Usage: " $3 " / " $2}'
        # 采集磁盘 I/O 使用情况
        iostat -d | grep "^sd" | awk '{print "Disk I/O (" $1 "): Read=" $4 "KB/s, Write=" $5 "KB/s"}'
        sleep 30
    done >> "$log_file" &

    # 记录脚本的 PID
    echo $! > /tmp/sys_monitor.pid
    echo "Monitoring script is running. PID: $(cat /tmp/sys_monitor.pid)"
fi

# 停止监控
if [ "$1" == "stop" ]; then
    if [ -f /tmp/sys_monitor.pid ]; then
        echo "Stopping system monitoring..."
        kill -9 $(cat /tmp/sys_monitor.pid)
        rm /tmp/sys_monitor.pid
        echo "Monitoring script has been stopped."
    else
        echo "Monitoring script is not currently running."
    fi
fi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值