非常实用的常用Linux运维Shell脚本

2023-12-18 16:12:51 浏览数 (1)

运维可以根据实际情况进行修改 mysql备份脚本

代码语言:javascript复制
#!/bin/bash
set -e

USER="backup"

PASSWORD="backup"

# 数据库数据目录 #

DATA_DIR="/data/mysql"

BIN_INDEX=$DATA_DIR"/mysql-bin.index"

# 备份目录 #

BACKUP_DIR="/data/backup/mysql"

BACKUP_LOG="/var/log/mysql/backup.log"

DATE=`date  "%Y%m%d"`

TIME=`date  "%Y%m%d%H"`

LOG_TIME=`date  "%Y-%m-%d %H:%M:%S"`

DELETE_BINLOG_TIME="7 day"

INCREMENT_INTERVAL="3 hour"

note() {

    printf "[$LOG_TIME] note: $*n" >> $BACKUP_LOG;

}

warning() {

    printf "[$LOG_TIME] warning: $*n" >> $BACKUP_LOG;

}

error() {

    printf "[$LOG_TIME] error: $*n" >> $BACKUP_LOG;

    exit 1;

}

full_backup() {

    local dbs=`ls -l $DATA_DIR | grep "^d" | awk -F " " '{print $9}'`

    for db in $dbs

    do

        local backup_dir=$BACKUP_DIR"/full/"$db

        local filename=$db"."$DATE

        local backup_file=$backup_dir"/"$filename".sql"

        if [ ! -d $backup_dir ]

        then

            mkdir -p $backup_dir || { error "创建数据库 $db 全量备份目录 $backup_dir 失败"; continue; }

            note "数据库 $db 全量备份目录 $backup_dir  不存在,创建完成";

        fi

        note "full backup $db start ..."

        mysqldump --user=${USER} --password=${PASSWORD} --flush-logs --skip-lock-tables --quick $db > $backup_file || { warning "数据库 $db 备份失败"; continue; }

        cd $backup_dir

        tar -cPzf $filename".tar.gz" $filename".sql"

        rm -f $backup_file

        chown -fR mysql:mysql $backup_dir

        note "数据库 $db 备份成功";

        note "full backup $db end."

    done

}

increment_backup() {

    local StartTime=`date "-d $INCREMENT_INTERVAL ago"  "%Y-%m-%d %H:%M:%S"`

    local DELETE_BINLOG_END_TIME=`date "-d $DELETE_BINLOG_TIME ago"  "%Y-%m-%d %H:%M:%S"`

    local dbs=`ls -l $DATA_DIR | grep "^d" | awk -F " " '{print $9}'`

    mysql -u$USER -p$PASSWORD -e "purge master logs before '$DELETE_BINLOG_END_TIME'" && note "delete $DELETE_BINLOG_TIME days before log";

    filename=`cat $BIN_INDEX | awk -F "/" '{print $2}'`

    for i in $filename

    do

        for db in $dbs

        do

            local backup_dir=$BACKUP_DIR"/increment/"$db

            local filename=$db"."$TIME

            local backup_file=$backup_dir"/"$filename".sql"

            if [ ! -d $backup_dir ]

            then

                mkdir -p $backup_dir || { error "创建数据库 $db 增量备份目录 $backup_dir 失败"; continue; }

                note "数据库 $db 增量备份目录 $backup_dir  不存在,创建完成";

            fi

            note "increment backup $db form time $StartTime start ..."

            mysqlbinlog -d $db --start-datetime="$StartTime" $DATA_DIR/$i >> $backup_file || { warning "数据库 $db 备份失败"; continue; }

            note "increment backup $db end."

        done

    done

    for db in $dbs

    do

        local backup_dir=$BACKUP_DIR"/increment/"$db

        local filename=$db"."$TIME

        local backup_file=$backup_dir"/"$filename".sql"

        cd $backup_dir

        tar -cPzf $filename".tar.gz" $filename".sql"

        rm -f $backup_file
        
        note "数据库 $db 备份成功";
    done
}

case "$1" in
    full)
        full_backup
    ;;
    increment)
        increment_backup
    ;;
    *)
        exit 2
    ;;
esac
exit 1

Dos 攻击防范(自动屏蔽攻击 IP)

代码语言:javascript复制
#!/bin/bash
DATE=$(date  %d/%b/%Y:%H:%M)
LOG_FILE=/usr/local/nginx/logs/demo2.access.log
ABNORMAL_IP=$(tail -n5000 $LOG_FILE |grep $DATE |awk '{a[$1]  }END{for(i in a)if(a[i]>10)print i}')
for IP in $ABNORMAL_IP; do
    if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
        iptables -I INPUT -s $IP -j DROP
        echo "$(date  '%F_%T') $IP" >> /tmp/drop_ip.log
    fi
done

Linux 系统发送告警脚本

代码语言:javascript复制
# yum install mailx
# vi /etc/mail.rc
set from=baojingtongzhi@163.com smtp=smtp.163.com
set smtp-auth-user=baojingtongzhi@163.com smtp-auth-password=*******
set smtp-auth=login

MySQL 数据库备份单循环

代码语言:javascript复制
#!/bin/bash
DATE=$(date  %F_%H-%M-%S)
HOST=localhost
USER=backup
PASS=123.com
BACKUP_DIR=/data/db_backup
DB_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "show databases;" 2>/dev/null |egrep -v "Database|information_schema|mysql|performance_schema|sys")

for DB in $DB_LIST; do
    BACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sql
    if ! mysqldump -h$HOST -u$USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null; then
        echo "$BACKUP_NAME 备份失败!"
    fi
done

MySQL 数据库备份多循环

代码语言:javascript复制
#!/bin/bash
DATE=$(date  %F_%H-%M-%S)
HOST=localhost
USER=backup
PASS=123.com
BACKUP_DIR=/data/db_backup
DB_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "show databases;" 2>/dev/null |egrep -v "Database|information_schema|mysql|performance_schema|sys")

for DB in $DB_LIST; do
    BACKUP_DB_DIR=$BACKUP_DIR/${DB}_${DATE}
    [ ! -d $BACKUP_DB_DIR ] && mkdir -p $BACKUP_DB_DIR &>/dev/null
    TABLE_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "use $DB;show tables;" 2>/dev/null)
    for TABLE in $TABLE_LIST; do
        BACKUP_NAME=$BACKUP_DB_DIR/${TABLE}.sql
        if ! mysqldump -h$HOST -u$USER -p$PASS $DB $TABLE > $BACKUP_NAME 2>/dev/null; then
            echo "$BACKUP_NAME 备份失败!"
        fi
    done
done

Nginx 访问访问日志按天切割

代码语言:javascript复制
#!/bin/bash
LOG_DIR=/usr/local/nginx/logs
YESTERDAY_TIME=$(date -d "yesterday"  %F)
LOG_MONTH_DIR=$LOG_DIR/$(date  "%Y-%m")
LOG_FILE_LIST="default.access.log"

for LOG_FILE in $LOG_FILE_LIST; do
    [ ! -d $LOG_MONTH_DIR ] && mkdir -p $LOG_MONTH_DIR
    mv $LOG_DIR/$LOG_FILE $LOG_MONTH_DIR/${LOG_FILE}_${YESTERDAY_TIME}
done

kill -USR1 $(cat /var/run/nginx.pid)

Nginx 访问日志分析脚本

代码语言:javascript复制
#!/bin/bash
# 日志格式: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"
LOG_FILE=$1
echo "统计访问最多的10个IP"
awk '{a[$1]  }END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10
echo "----------------------"

echo "统计时间段访问最多的IP"
awk '$4>="[01/Dec/2018:13:20:25" && $4<="[27/Nov/2018:16:20:49"{a[$1]  }END{for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr|head -10
echo "----------------------"

echo "统计访问最多的10个页面"
awk '{a[$7]  }END{print "PV:",length(a);for(v in a){if(a[v]>10)print v,a[v]}}' $LOG_FILE |sort -k2 -nr
echo "----------------------"

echo "统计访问页面状态码数量"
awk '{a[$7" "$9]  }END{for(v in a){if(a[v]>5)print v,a[v]}}'

查看网卡实时流量脚本

代码语言:javascript复制
#!/bin/bash
NIC=$1
echo -e " In ------ Out"
while true; do
    OLD_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
    OLD_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
    sleep 1
    NEW_IN=$(awk  '$0~"'$NIC'"{print $2}' /proc/net/dev)
    NEW_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
    IN=$(printf "%.1f%s" "$((($NEW_IN-$OLD_IN)/1024))" "KB/s")
    OUT=$(printf "%.1f%s" "$((($NEW_OUT-$OLD_OUT)/1024))" "KB/s")
    echo "$IN $OUT"
    sleep 1
done

服务器系统配置初始化脚本

代码语言:javascript复制
#/bin/bash
# 设置时区并同步时间
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
if ! crontab -l |grep ntpdate &>/dev/null ; then
    (echo "* 1 * * * ntpdate time.windows.com >/dev/null 2>&1";crontab -l) |crontab
fi

# 禁用selinux
sed -i '/SELINUX/{s/permissive/disabled/}' /etc/selinux/config

# 关闭防火墙
if egrep "7.[0-9]" /etc/redhat-release &>/dev/null; then
    systemctl stop firewalld
    systemctl disable firewalld
elif egrep "6.[0-9]" /etc/redhat-release &>/dev/null; then
    service iptables stop
    chkconfig iptables off
fi

# 历史命令显示操作时间
if ! grep HISTTIMEFORMAT /etc/bashrc; then
    echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/bashrc
fi

# SSH超时时间
if ! grep "TMOUT=600" /etc/profile &>/dev/null; then
    echo "export TMOUT=600" >> /etc/profile
fi

# 禁止root远程登录
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config

# 禁止定时任务向发送邮件
sed -i 's/^MAILTO=root/MAILTO=""/' /etc/crontab

# 设置最大打开文件数
if ! grep "* soft nofile 65535" /etc/security/limits.conf &>/dev/null; then
    cat >> /etc/security/limits.conf << EOF
    * soft nofile 65535
    * hard nofile 65535
EOF
fi

# 系统内核优化
cat >> /etc/sysctl.conf << EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_tw_buckets = 20480
net.ipv4.tcp_max_syn_backlog = 20480
net.core.netdev_max_backlog = 262144
net.ipv4.tcp_fin_timeout = 20
EOF

# 减少SWAP使用
echo "0" > /proc/sys/vm/swappiness

# 安装系统性能分析工具及其他
yum install gcc make autoconf vim sysstat net-tools iostat if

监控 100 台服务器磁盘利用率脚本

代码语言:javascript复制
#!/bin/bash
HOST_INFO=host.info
for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
    USER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)
    PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)
    TMP_FILE=/tmp/disk.tmp
    ssh -p $PORT $USER@$IP 'df -h' > $TMP_FILE
    USE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^/dev/{print $NF,int($5)}' $TMP_FILE)
    for USE_RATE in $USE_RATE_LIST; do
        PART_NAME=${USE_RATE%=*}
        USE_RATE=${USE_RATE#*=}
        if [ $USE_RATE -ge 80 ]; then
            echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
        fi
    done
done

mysqldump备份所有库脚本

代码语言:javascript复制
#!/bin/bash
date=`date  %Y_%m_%d'___'%H_%M_%S`
#######################################
project_path=$(cd `dirname $0`; pwd)
#######################################
start_time=`date --date='0 days ago' " %Y-%m-%d %H:%M:%S"`
u="puser"
p="!O2222n"
ip="127.0.0.1"
port="3306"
pwd="/opt/Myslq_Backup"
mysql -u$u -p$p "-e show databases;" |awk '{print $1}' |egrep -v -e "Database" -e  "performance_schema" -e "information_schema"  > $pwd/Database_text
for i in `(cat  $pwd/Database_text)`
do
        mysqldump  -u$u -p$p   $i  > $pwd/${i}_$date.sql
        gzip  $pwd/${i}_$date.sql
done
find   $pwd/    -mtime  30   -name "*.gz" -exec rm -rf {} ;
finish_time=`date --date='0 days ago' " %Y-%m-%d %H:%M:%S"`
duration=$(($(($(date  %s -d "$finish_time")-$(date  %s -d "$start_time")))))
echo -e "33[41m 本次执行脚本耗时: $duration秒 33[0m"

0 人点赞