Linux运维,常用自动化shell脚本编写案例

2026-9-17 118 9/17

日志备份脚本,这里是mysql数据库备份

#!/bin/bash
ntime=$(date +%Y%m%d%H%M)

mysqldump -uadmin -p'passwrod' opencart > /mybackup/opencart.sql 2>/dev/null

tar -czf /mybackup/tar-$ntime.tar.gz -C /mybackup opencart.sql
rm -f /mybackup/opencart.sql

mountpoint -q /mnt/nfs_share && rsync /mybackup/*.tar.gz /mnt/nfs_share/

find /mybackup -type f -mtime +30 -delete

echo "well done! complete time $ntime" >> /shell/mybackup.log


#-----------------------------------------------------------------

 

 

邮件发送服务的快速配置脚本

#!/bin/bash
# FileName: smtp.sh
# version: 1.0
# Date: 2026-9-17
# Author: sanopll-copy
# Descriptions: for smtp configuration
# 描述: 配置smtp邮件发送服务

read -p "Please Input You Email Provider [163/qq/126]: " provider
read -p "Please Input You Email Account: " account
read -p "Please Input You Auth-Password: " password

echo "Waiting For A mount..."

yum install mailx sendmail -y >/dev/null

cat >> /etc/mail.rc<< EOF
set from=$account@$provider.com       
set smtp=smtp.$provider.com            
set smtp-auth-user=$account             
set smtp-auth-password=$password       
set smtp-auth=login                  
EOF

systemctl start sendmail


#-----------------------------------------------------

 

分析访问日志,统计出现次数最多的IP的访问次数,若大于一定次数则告

#!/bin/bash

name=$(hostname)
logfile=/shell/log/access.log

[ -f "$logfile" ] || exit 1

result=$(awk '{print $1}' "$logfile" | sort | uniq -c | sort -rn | head -1)
largcon=$(echo "$result" | awk '{print $1}')
largip=$(echo "$result" | awk '{print $2}')

echo "$(date +'%m月%d日 %H时%M分') 最大连接数 $largcon,IP $largip" >> /shell/log/anti-dos.log

if [ "$largcon" -gt 10000 ]; then
    echo "警告:服务器 $name 受到攻击,连接数 $largcon,IP $largip" | \
    mail -s '服务器受DoS攻击警告' sanopll@163.com
fi


#--------------------------------------------------------

 

 

Nginx服务状态监控脚本,死循环每隔3秒检测一次80端口

#!/bin/bash

while true; do
    if ! ss -lntp | grep -q ':80 '; then
        echo "$(date +%y年%m月%d日%H时%M分%S秒) - nginx停止运行,正在重启" \
        | tee -a /shell/log/nginx_error.log
        systemctl restart nginx
    else
        echo "$(date +%y年%m月%d日%H时%M分%S秒) - nginx正常运行" \
        >> /shell/log/nginx_normal.log
    fi
    sleep 3
done

 

 

 

 

 

 

- THE END -

sanoplluser

9月28日20:44

最后修改:2026年9月28日
0

共有 0 条评论