配置开机和SSH登录自动显示系统状态
1,创建目录
cd /
mkdir /LogIn
cd /LogIn
2,创建sh脚本
vi sysinfo.sh
# 输入下面文件,直接复制
#!/bin/bash
# 系统资源概览脚本 – 开机/登录时自动显示
# 要求:bash 4.0+,已安装 procps(ps, free, top)和 iproute2
# 颜色定义(提高可读性)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m' # No Color
# 分隔线函数
separator() {
printf "${BLUE}%$(tput cols)s${NC}\n" | tr ' ' '='
}
# 标题函数
title() {
echo -e "${BOLD}${BLUE}== $1 ==${NC}"
}
# 1. CPU 使用率
cpu_info() {
# 使用 top 获取 1 秒采样,避免长时延迟
local cpu_line
cpu_line=$(top -bn2 -d 0.1 | grep '%Cpu' | tail -1)
local user sys idle iowait
user=$(echo "$cpu_line" | awk '{print $2}')
sys=$(echo "$cpu_line" | awk '{print $4}')
idle=$(echo "$cpu_line" | awk '{print $8}')
iowait=$(echo "$cpu_line" | awk '{print $10}')
echo -e "${GREEN}用户态:${NC} $user% ${GREEN}系统态:${NC} $sys% ${GREEN}空闲:${NC} $idle% ${GREEN}I/O等待:${NC} $iowait%"
}
# 2. 内存信息(人类可读)
mem_info() {
free -h | awk 'NR==2{printf "总内存: %s 已用: %s 空闲: %s 缓存/缓冲: %s 可用: %s\n", $2, $3, $4, $6, $7}'
echo -n "Swap: "
free -h | awk 'NR==3{printf "总: %s 已用: %s 空闲: %s\n", $2, $3, $4}'
}
# 3. 磁盘使用(常用挂载点)
disk_info() {
# 显示根目录和 /home(如果独立分区),可自行扩展
df -h / /home 2>/dev/null | awk 'NR>1 {printf "%-20s %5s 已用/共 %-8s 已用%% %s\n", $6, $3"/"$2, $5, $1}'
}
# 4. 网络接口信息(IP 和累计流量)
net_info() {
# 获取所有非回环的 IPv4 地址
local ifaces ip_addr
echo "接口 IP地址 接收/发送数据量"
for iface in $(ip -o link show | awk -F': ' '{print $2}' | grep -v lo); do
ip_addr=$(ip -o -4 addr show "$iface" | awk '{print $4}' | cut -d/ -f1)
# 获取收发字节数(累计)
rx_bytes=$(ip -s link show "$iface" | grep -A1 "RX:" | tail -1 | awk '{print $1}')
tx_bytes=$(ip -s link show "$iface" | grep -A1 "TX:" | tail -1 | awk '{print $1}')
rx_h=$(numfmt --to=iec "$rx_bytes" 2>/dev/null || echo "$rx_bytes B")
tx_h=$(numfmt --to=iec "$tx_bytes" 2>/dev/null || echo "$tx_bytes B")
printf "%-12s %-25s 收: %8s 发: %8s\n" "$iface" "${ip_addr:-无IP}" "$rx_h" "$tx_h"
done
}
# 主输出
clear
separator
title "系统资源概览 ( $(date '+%Y-%m-%d %H:%M:%S') )"
separator
echo -e "\n${BOLD}🖥️ CPU 状态${NC}"
cpu_info
echo -e "\n${BOLD}💾 内存状态${NC}"
mem_info
echo -e "\n${BOLD}💿 磁盘使用${NC}"
disk_info
echo -e "\n${BOLD}🌐 网络状态${NC}"
net_info
separator
echo -e "${YELLOW}提示:此信息为开机/登录时快照。如需实时监控,请使用 htop、nload 等工具。${NC}"
echo
3,导入设置开机启动
#直接复制以下内容
echo '/LogIn/sysinfo.sh' >>/.profile
echo -e '\n# 显示系统信息\n/kjjc/sysinfo.sh' >> ~/.bash_profile
4,预期结果
===================================================================================
== 系统资源概览 ( 2026-03-27 21:20:45 ) ==
===================================================================================
🖥️ CPU 状态
用户态: 0.0% 系统态: 4.5% 空闲: 95.5% I/O等待: 0.0%
💾 内存状态
总内存: 1.7Gi 已用: 383Mi 空闲: 1.3Gi 缓存/缓冲: 204Mi 可用: 1.3Gi
Swap: 总: 2.0Gi 已用: 0B 空闲: 2.0Gi
💿 磁盘使用
/ 3.2G/47G 已用/共 7% 已用% /dev/mapper/cs-root
/ 3.2G/47G 已用/共 7% 已用% /dev/mapper/cs-root
🌐 网络状态
接口 IP地址 接收/发送数据量
ens160 192.168.198.132 收: 73K 发: 116K
===================================================================================
提示:此信息为开机/登录时快照。如需实时监控,请使用 htop、nload 等工具。