一个简单的Shell脚本示例,用于监控服务器的性能指标:
!/bin/bash
获取CPU使用率
function get_cpu_usage() {
cpu_usage=$(top -bn1 | awk '/Cpu\(s\):/ {print $2}')
echo "CPU使用率:$cpu_usage"
}
获取内存使用情况
function get_memory_usage() {
memory_usage=$(free -m | awk '/Mem:/ {print $3}')
memory_total=$(free -m | awk '/Mem:/ {print $2}')
memory_percentage=$(awk "BEGIN {printf \"%.2f\", ${memory_usage} / ${memory_total} * 100}")
echo "内存使用情况:${memory_usage}M / ${memory_total}M (${memory_percentage}%)"
}
获取磁盘使用情况
function get_disk_usage() {
disk_usage=$(df -h / | awk '/^Filesystem/ {print $5}')
echo "磁盘使用情况:$disk_usage"
}
获取网络连接数
function get_network_connections() {
active_connections=$(netstat -an | awk '/ESTABLISHED|TIME_WAIT|CLOSE_WAIT/ {print $1}')
echo "网络连接数:$active_connections"
}
获取系统负载
function get_system_load() {
load_average=$(uptime | awk -F 'load average:' '{print $2}')
echo "系统负载:$load_average"
}
获取系统运行时间
function get_uptime() {
uptime_seconds=$(cut -d. -f1 /proc/uptime)
uptime_hours=$(awk "BEGIN {printf \"%.2f\", ${uptime_seconds} / 3600}")
echo "系统运行时间:${uptime_hours}小时"
}
执行性能监控
get_cpu_usage
get_memory_usage
get_disk_usage
get_network_connections
get_system_load
get_uptime