以下脚本可谓日常工作常用到的经典脚本案例。希望可以帮助大家提升提升自动化能力!
1、监控100台服务器磁盘利用率脚本
#!/bin/bashHOST_INFO=host.infofor IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); doUSER=$(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.tmpssh -p $PORT $USER@$IP 'df -h' > $TMP_FILEUSE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^\/dev/{print $NF,int($5)}' $TMP_FILE)for USE_RATE in $USE_RATE_LIST; doPART_NAME=${USE_RATE%=*}USE_RATE=${USE_RATE#*=}if [ $USE_RATE -ge 80 ]; thenecho "Warning: $PART_NAME Partition usage $USE_RATE%!"fidonedone
2、监控MySQL主从同步状态是否异常脚本
#!/bin/bashHOST=localhostUSER=rootPASSWD=123.comIO_SQL_STATUS=$(mysql -h$HOST -u$USER -p$PASSWD -e 'show slave status\G' 2>/dev/null |awk '/Slave_.*_Running:/{print $1$2}')for i in $IO_SQL_STATUS; doTHREAD_STATUS_NAME=${i%:*}THREAD_STATUS=${i#*:}if [ "$THREAD_STATUS" != "Yes" ]; thenecho "Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!" |mail -s "Master-Slave Staus" xxx@163.comfidone
3、MySQL数据库备份单循环
#!/bin/bashDATE=$(date +%F_%H-%M-%S)HOST=localhostUSER=backupPASS=123.comBACKUP_DIR=/data/db_backupDB_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; doBACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sqlif ! mysqldump -h$HOST -u$USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null; thenecho "$BACKUP_NAME 备份失败!"fidone
4、MySQL数据库备份多循环
#!/bin/bashDATE=$(date +%F_%H-%M-%S)HOST=localhostUSER=backupPASS=123.comBACKUP_DIR=/data/db_backupDB_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; doBACKUP_DB_DIR=$BACKUP_DIR/${DB}_${DATE}[ ! -d $BACKUP_DB_DIR ] && mkdir -p $BACKUP_DB_DIR &>/dev/nullTABLE_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "use $DB;show tables;" 2>/dev/null)for TABLE in $TABLE_LIST; doBACKUP_NAME=$BACKUP_DB_DIR/${TABLE}.sqlif ! mysqldump -h$HOST -u$USER -p$PASS $DB $TABLE > $BACKUP_NAME 2>/dev/null; thenecho "$BACKUP_NAME 备份失败!"fidonedone
5、Dos攻击防范(自动屏蔽攻击IP)
#!/bin/bashDATE=$(date +%d/%b/%Y:%H:%M)LOG_FILE=/usr/local/nginx/logs/demo2.access.logABNORMAL_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; doif [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; theniptables -I INPUT -s $IP -j DROPecho "$(date +'%F_%T') $IP" >> /tmp/drop_ip.logfidone
6、Linux系统发送告警脚本
# yum install mailx# vi /etc/mail.rcset from=baojingtongzhi@163.com smtp=smtp.163.comset smtp-auth-user=baojingtongzhi@163.com smtp-auth-password=123456set smtp-auth=login
7、nginx 访问访问日志按天切割
#!/bin/bashLOG_DIR=/usr/local/nginx/logsYESTERDAY_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_DIRmv $LOG_DIR/$LOG_FILE $LOG_MONTH_DIR/${LOG_FILE}_${YESTERDAY_TIME}donekill -USR1 $(cat /var/run/nginx.pid)
8、nginx访问日志分析脚本
#!/bin/bash# 日志格式: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"LOG_FILE=$1echo "统计访问最多的10个IP"awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10echo "----------------------"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 -10echo "----------------------"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 -nrecho "----------------------"echo "统计访问页面状态码数量"awk '{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}' $LOG_FILE |sort -k3 -nr
9、查看网卡实时流量脚本
#!/bin/bashNIC=$1echo -e " In ------ Out"while true; doOLD_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)OLD_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)sleep 1NEW_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 1done
10、服务器系统配置初始化脚本
#/bin/bash# 设置时区并同步时间ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtimeif ! crontab -l |grep ntpdate &>/dev/null ; then(echo "* 1 * * * ntpdate time.windows.com >/dev/null 2>&1";crontab -l) |crontabfi# 禁用selinuxsed -i '/SELINUX/{s/permissive/disabled/}' /etc/selinux/config# 关闭防火墙if egrep "7.[0-9]" /etc/redhat-release &>/dev/null; thensystemctl stop firewalldsystemctl disable firewalldelif egrep "6.[0-9]" /etc/redhat-release &>/dev/null; thenservice iptables stopchkconfig iptables offfi# 历史命令显示操作时间if ! grep HISTTIMEFORMAT /etc/bashrc; thenecho 'export HISTTIMEFORMAT="%F %T `whoami` "' >> /etc/bashrcfi# SSH超时时间if ! grep "TMOUT=600" /etc/profile &>/dev/null; thenecho "export TMOUT=600" >> /etc/profilefi# 禁止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; thencat >> /etc/security/limits.conf << EOF* soft nofile 65535* hard nofile 65535EOFfi# 系统内核优化cat >> /etc/sysctl.conf << EOFnet.ipv4.tcp_syncookies = 1net.ipv4.tcp_max_tw_buckets = 20480net.ipv4.tcp_max_syn_backlog = 20480net.core.netdev_max_backlog = 262144net.ipv4.tcp_fin_timeout = 20EOF# 减少SWAP使用echo "0" > /proc/sys/vm/swappiness# 安装系统性能分析工具及其他yum install gcc make autoconf vim sysstat net-tools iostat iftop iotp lrzsz -y
11、目录文件变化监控和实时文件同步
#!/bin/bashMON_DIR=/optinotifywait -mqr --format %f -e create $MON_DIR |\while read files; dorsync -avz /opt /tmp/opt#echo "$(date +'%F %T') create $files" | mail -s "dir monitor" xxx@163.comdone
12、批量创建100用户并设置密码脚本
#!/bin/bashDATE=$@USER_FILE=user.txtfor USER in $USER_LIST; doif ! id $USER &>/dev/null; thenPASS=$(echo $RANDOM |md5sum |cut -c 1-8)useradd $USERecho $PASS |passwd --stdin $USER &>/dev/nullecho "$USER $PASS" >> $USER_FILEecho "$USER User create successful."elseecho "$USER User already exists!"fidone
13、批量检测网站是否异常脚本
#!/bin/bashURL_LIST="www.baidu.com www.ctnrs.com"for URL in $URL_LIST; doFAIL_COUNT=0for ((i=1;i<=3;i++)); doHTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL)if [ $HTTP_CODE -eq 200 ]; thenecho "$URL OK"breakelseecho "$URL retry $FAIL_COUNT"let FAIL_COUNT++fidoneif [ $FAIL_COUNT -eq 3 ]; thenecho "Warning: $URL Access failure!"fidone
14、批量主机远程执行命令脚本
#!/bin/bashCOMMAND=$*HOST_INFO=host.infofor IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); doUSER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)PASS=$(awk -v ip=$IP 'ip==$1{print $4}' $HOST_INFO)expect -c "spawn ssh -p $PORT $USER@$IPexpect {\"(yes/no)\" {send \"yes\r\"; exp_continue}\"password:\" {send \"$PASS\r\"; exp_continue}\"$USER@*\" {send \"$COMMAND\r exit\r\"; exp_continue}}"echo "-------------------"done
15、一键部署LNMP网站平台脚本
#!/bin/bashNGINX_V=1.15.6PHP_V=5.6.36TMP_DIR=/tmpINSTALL_DIR=/usr/localPWD_C=$PWDechoecho -e "\tMenu\n"echo -e "1. Install Nginx"echo -e "2. Install PHP"echo -e "3. Install MySQL"echo -e "4. Deploy LNMP"echo -e "9. Quit"function command_status_check() {if [ $? -ne 0 ]; thenecho $1exitfi}function install_nginx() {cd $TMP_DIRyum install -y gcc gcc-c++ make openssl-devel pcre-devel wgetwget http://nginx.org/download/nginx-${NGINX_V}.tar.gztar zxf nginx-${NGINX_V}.tar.gzcd nginx-${NGINX_V}./configure --prefix=$INSTALL_DIR/nginx \--with-http_ssl_module \--with-http_stub_status_module \--with-streamcommand_status_check "Nginx - 平台环境检查失败!"make -j 4command_status_check "Nginx - 编译失败!"make installcommand_status_check "Nginx - 安装失败!"mkdir -p $INSTALL_DIR/nginx/conf/vhostalias cp=cp ; cp -rf $PWD_C/nginx.conf $INSTALL_DIR/nginx/confrm -rf $INSTALL_DIR/nginx/html/*echo "ok" > $INSTALL_DIR/nginx/html/status.htmlecho '<?php echo "ok"?>' > $INSTALL_DIR/nginx/html/status.php$INSTALL_DIR/nginx/sbin/nginxcommand_status_check "Nginx - 启动失败!"}function install_php() {cd $TMP_DIRyum install -y gcc gcc-c++ make gd-devel libxml2-devel \libcurl-devel libjpeg-devel libpng-devel openssl-devel \libmcrypt-devel libxslt-devel libtidy-develwget http://docs.php.net/distributions/php-${PHP_V}.tar.gztar zxf php-${PHP_V}.tar.gzcd php-${PHP_V}./configure --prefix=$INSTALL_DIR/php \--with-config-file-path=$INSTALL_DIR/php/etc \--enable-fpm --enable-opcache \--with-mysql --with-mysqli --with-pdo-mysql \--with-openssl --with-zlib --with-curl --with-gd \--with-jpeg-dir --with-png-dir --with-freetype-dir \--enable-mbstring --enable-hashcommand_status_check "PHP - 平台环境检查失败!"make -j 4command_status_check "PHP - 编译失败!"make installcommand_status_check "PHP - 安装失败!"cp php.ini-production $INSTALL_DIR/php/etc/php.inicp sapi/fpm/php-fpm.conf $INSTALL_DIR/php/etc/php-fpm.confcp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpmchmod +x /etc/init.d/php-fpm/etc/init.d/php-fpm startcommand_status_check "PHP - 启动失败!"}read -p "请输入编号:" numbercase $number in1)install_nginx;;2)install_php;;3)install_mysql;;4)install_nginxinstall_php;;9)exit;;esac
16、一键查看服务器资源利用率
#!/bin/bashfunction cpu() {NUM=1while [ $NUM -le 3 ]; doutil=`vmstat |awk '{if(NR==3)print 100-$15"%"}'`user=`vmstat |awk '{if(NR==3)print $13"%"}'`sys=`vmstat |awk '{if(NR==3)print $14"%"}'`iowait=`vmstat |awk '{if(NR==3)print $16"%"}'`echo "CPU - 使用率: $util , 等待磁盘IO响应使用率: $iowait"let NUM++sleep 1done}function memory() {total=`free -m |awk '{if(NR==2)printf "%.1f",$2/1024}'`used=`free -m |awk '{if(NR==2) printf "%.1f",($2-$NF)/1024}'`available=`free -m |awk '{if(NR==2) printf "%.1f",$NF/1024}'`echo "内存 - 总大小: ${total}G , 使用: ${used}G , 剩余: ${available}G"}function disk() {fs=$(df -h |awk '/^\/dev/{print $1}')for p in $fs; domounted=$(df -h |awk '$1=="'$p'"{print $NF}')size=$(df -h |awk '$1=="'$p'"{print $2}')used=$(df -h |awk '$1=="'$p'"{print $3}')used_percent=$(df -h |awk '$1=="'$p'"{print $5}')echo "硬盘 - 挂载点: $mounted , 总大小: $size , 使用: $used , 使用率: $used_percent"done}function tcp_status() {summary=$(ss -antp |awk '{status[$1]++}END{for(i in status) printf i":"status[i]" "}')echo "TCP连接状态 - $summary"}cpumemorydisktcp_status
17、找出占用CPU 内存过高的进程脚本
ps -eo user,pid,pcpu,pmem,args --sort=-pcpu |head -n 10ps -eo user,pid,pcpu,pmem,args --sort=-pmem |head -n 10