Linux中常用的Shell脚本(运维+常用)汇总

废话不多说,直接上干货!

一、运维脚本

(1)监控CPU和内存的使用情况

复制代码
#!/bin/bash

cpu_threshold=80
mem_threshold=80

# 获取CPU和内存使用率
cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

# 检查CPU使用率
if (( $(echo "$cpu_usage > $cpu_threshold" | bc -l) )); then
    echo "CPU usage is above threshold: $cpu_usage%"
fi

# 检查内存使用率
if (( $(echo "$mem_usage > $mem_threshold" | bc -l) )); then
    echo "Memory usage is above threshold: $mem_usage%"
fi

(2)定期备份到指定目录脚本

复制代码
#!/bin/bash

backup_source="/path/to/source"
backup_dest="/path/to/backup"
timestamp=$(date +"%Y%m%d%H%M")

# 创建备份
tar -czf "$backup_dest/backup_$timestamp.tar.gz" -C "$backup_source" .

# 删除7天前的备份
find "$backup_dest" -type f -name "*.tar.gz" -mtime +7 -exec rm {} \;

(3)自动轮转、压缩和删除旧日志

复制代码
#!/bin/bash

log_file="/var/log/myapp.log"
max_size=10485760  # 10 MB

if [ -f "$log_file" ]; then
    log_size=$(stat -c%s "$log_file")
    if [ "$log_size" -ge "$max_size" ]; then
        mv "$log_file" "$log_file.old"
        touch "$log_file"
        gzip "$log_file.old"
    fi
fi

(4)磁盘监控脚本

复制代码
#!/bin/bash

threshold=90
df -H | awk '{if ($5 > threshold) print $0}' | while read line; do
    echo "Disk space alert: $line"
done

二、常用其他脚本

(1)输出不同颜色的提示语

复制代码
#打印不同颜色方法
echo_color() {
	if [ $1 == "green" ]; then
		echo -e "\033[32;40m$2\033[0m"
	elif [ $1 == "red" ]; then
		echo -e "\033[31;40m$2\033[0m"
	elif [ $1 == "yellow" ]; then
		echo -e "\033[33;40m$2\033[0m"
	elif [ $1 == "blue" ]; then
		echo -e "\033[34;40m$2\033[0m"
	fi
}

(2)检测IP格式合规性

复制代码
# 函数:检测IP格式
is_valid_ip() {
    local ip="$1"
    [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
}

(3)检测端口合规性

复制代码
# 函数:检测端口号
is_valid_port() {
    local port="$1"
    [[ "$port" =~ ^[0-9]+$ ]] && [ "$port" -ge 1 ] && [ "$port" -le 65535 ] && return 0 || return 1
}

(4)检测某端口是否已存在

复制代码
check_port(){
	check_port=$1
	check_result="$(netstat -tunlp|grep -w ${check_port} |awk '{print $7}'|cut -d/ -f1)"
	if [[ -n "$check_result" ]];then
		echo "$check_port端口已被占用"
		exit 1
    else
	  echo "端口:$check_port,可用"
	fi
}

(5)设置某个服务开机自启动

复制代码
#根据服务名称设置服务开机自启动
set_service_on(){
  service_name=$1
  chmod 644 /lib/systemd/system/${service_name}.service
  chown root:root /lib/systemd/system/${service_name}.service
  systemctl daemon-reload
  systemctl restart ${service_name}
  systemctl enable ${service_name}
}

(6)获取当前服务器时间(标准格式)

复制代码
time=`date "+%Y-%m-%d^%H:%M:%S"`

(7)检查服务在线状态(端口和进程)

复制代码
#被检测服务的端口号
PORT="10000"
#被检测服务的java程序
COUNT="$(ps -ef|grep "xxxxxxxxxxxxxxxxx.jar"|grep -v grep|wc -l)"
if [[ -n "$PORT" ]];then
  echo "服务正常启动"
elif [[ $COUNT -eq 1 ]]; then
  echo "服务正在启动中,请稍后... ..."
else
  echo "服务异常,请重启服务"
fi

(8)执行简单的定时任务

复制代码
while true; do
    echo "Running task at $(date)"
    sleep 60  # 每60秒执行一次
done

(9)并行执行多个命令

复制代码
{
    sleep 2
    echo "Task 1 completed"
} & {
    sleep 3
    echo "Task 2 completed"
}
wait  # 等待所有后台任务完成
echo "All tasks completed."

(10)使用条件语句进行文件(文件夹)判别

复制代码
if [ -f "myfile.txt" ]; then
    echo "File exists."
elif [ -d "mydir" ]; then
    echo "It's a directory."
else
    echo "File or directory does not exist."
fi

若有需要帮忙写的Shell脚本,可以留言!

相关推荐
wj3055853788 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
abigriver8 小时前
打造 Linux 离线大模型级语音输入法:Whisper.cpp + 3090 显卡加速与 Rime 中英混输终极调优指南
linux·运维·whisper
wangqiaowq8 小时前
windows下nginx的安装
linux·服务器·前端
YYRAN_ZZU9 小时前
Petalinux新建自动脚本启动
linux
charlie1145141919 小时前
嵌入式Linux驱动开发pinctrl篇(1)——从寄存器到子系统:驱动演进之路
linux·运维·驱动开发
Agent手记9 小时前
异常考勤智能预警与处理与流程优化方案 | 基于企业级Agent的超自动化实战教程
运维·人工智能·ai·自动化
于小猿Sup10 小时前
VMware在Ubuntu22.04驱动Livox Mid360s
linux·c++·嵌入式硬件·自动驾驶
cen__y10 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
不仙52011 小时前
VMware Workstation 26.0.0 在 Ubuntu 24.04 (内核 6.17.0) 上的安装与内核模块编译问题
linux·ubuntu·elasticsearch
1892280486112 小时前
NY352固态MT29F32T08GWLBHD6-24QJ:B
大数据·服务器·人工智能·科技·缓存