shell脚本,功能是检查服务器cpu,内存,已安装的软件列表,网络情况,服务器性能,服务器安全性,以及当前占用服务器资源前三名的应用程序。为了使脚本支持各种 Linux 系统,可以通过使用不同的命令和参数来执行所需操作。以下是一个优化后的脚本示例,用于检查服务器的各项情况和性能:
#! /bin/bash
# Check if the script is being run as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
#############################
# Check System Information #
#############################
echo "=== CPU INFORMATION ==="
if [[ -n $(command -v lscpu) ]]; then
lscpu | grep "Model name"
else
cat /proc/cpuinfo | grep "model name" | head -n1
fi
echo ""
echo "=== MEMORY INFORMATION ==="
if [[ -n $(command -v free) ]]; then
free -h
else
cat /proc/meminfo | grep "MemTotal"
fi
echo ""
echo "=== INSTALLED SOFTWARE ==="
if [[ -n $(command -v dpkg) ]]; then
dpkg -l
else
rpm -qa
fi
echo ""
echo "=== NETWORK INFORMATION ==="
if [[ -n $(command -v ifconfig) ]]; then
ifconfig
else
ip address
fi
echo ""
echo "=== SYSTEM PERFORMANCE ==="
uptime
echo ""
echo "=== SERVER SECURITY ==="
if [[ -n $(command -v apt-get) ]]; then
apt-get update && apt-get upgrade
elif [[ -n $(command -v yum) ]]; then
yum update
else
echo "Unsupported package manager."
fi
echo ""
echo "=== TOP 3 CONSUMING APPLICATIONS ==="
if [[ -n $(command -v ps) ]]; then
ps aux --sort=-%cpu | head -n 4
else
echo "Unable to retrieve running processes."
fi
此优化版脚本使用了 command -v
来检查当前系统中是否存在指定的命令。如果该命令存在,就执行相应的命令来获取所需信息;否则,就使用备选命令来获取相应信息。
需要注意的是,不同的 Linux 发行版可能采用不同的命令和参数,因此在编写和测试脚本时,需要选用良好的方法和适当的测试环境,以确保脚本的正确性和可靠性。