Write a Shell script to monitor whether memory overflows

Table of contents

1 implementation

#!/bin/bash

# 设置内存阈值(以KB为单位)
threshold=90

# 获取内存使用情况
memory=$(free -k | awk 'NR==2{
    
    print $3}')

# 检查内存使用是否超过阈值
if [ $memory -gt $threshold ]; then
  echo "内存使用超过阈值!当前使用内存: $memory KB"
  # 在此处添加发送警报的逻辑,例如发送邮件或调用其他通知机制
else
  echo "内存使用正常。当前使用内存: $memory KB"
fi

Script description:

The threshold variable is used to set the threshold of memory usage. Here it is set to 90, which means an alarm is triggered when the memory usage exceeds 90%.

Use the free -k command to get the server's memory usage, and use the awk command to extract the third column of the second row (used memory).

Compare the obtained memory usage with the threshold, and if the threshold is exceeded, an alert message is output.

In place of the alert logic, you can add code to send the alert if needed, such as sending an email or calling another notification mechanism.

You can save the above script as a file (for example, monitor_memory.sh), and then set up a scheduled task on the server (for example, using cron) to execute the script regularly. This enables regular monitoring of server memory overflows and triggers alerts when thresholds are reached.

Guess you like

Origin blog.csdn.net/python113/article/details/132214661