运维 Shell

1、服务器系统配置初始化

  1. #/bin/bash
  2. # 安装系统性能分析工具及其他
  3. yum install gcc make autoconf vim sysstat net-tools iostat iftop iotp wget lrzsz lsof unzip openssh-clients net-tool vim ntpdate -y
  4. # 设置时区并同步时间
  5. ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
  6. if ! crontab -l |grep ntpdate &>/dev/null ; then
  7. (echo "* 1 * * * ntpdate time.windows.com >/dev/null 2>&1";crontab -l) |crontab
  8. fi
  9. # 禁用selinux
  10. sed -i '/SELINUX/{s/permissive/disabled/}' /etc/selinux/config
  11. # 关闭防火墙
  12. if egrep "7.[0-9]" /etc/redhat-release &>/dev/null; then
  13. systemctl stop firewalld
  14. systemctl disable firewalld
  15. elif egrep "6.[0-9]" /etc/redhat-release &>/dev/null; then
  16. service iptables stop
  17. chkconfig iptables off
  18. fi
  19. # 历史命令显示操作时间
  20. if ! grep HISTTIMEFORMAT /etc/bashrc; then
  21. echo 'export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S `whoami` "' >> /etc/bashrc
  22. fi
  23. # SSH超时时间
  24. if ! grep "TMOUT=600" /etc/profile &>/dev/null; then
  25. echo "export TMOUT=600" >> /etc/profile
  26. fi
  27. # 禁止root远程登录 切记给系统添加普通用户,给su到root的权限
  28. sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
  29. # 禁止定时任务向发送邮件
  30. sed -i 's/^MAILTO=root/MAILTO=""/' /etc/crontab
  31. # 设置最大打开文件数
  32. if ! grep "* soft nofile 65535" /etc/security/limits.conf &>/dev/null; then
  33. cat >> /etc/security/limits.conf << EOF
  34. * soft nofile 65535
  35. * hard nofile 65535
  36. EOF
  37. fi
  38. # 系统内核优化
  39. cat >> /etc/sysctl.conf << EOF
  40. net.ipv4.tcp_syncookies = 1
  41. net.ipv4.tcp_max_tw_buckets = 20480
  42. net.ipv4.tcp_max_syn_backlog = 20480
  43. net.core.netdev_max_backlog = 262144
  44. net.ipv4.tcp_fin_timeout = 20
  45. EOF
  46. # 减少SWAP使用
  47. echo "0" > /proc/sys/vm/swappiness

2、批量创建多个用户并设置密码

  1. #!/bin/bash
  2. USER_LIST=$@
  3. USER_FILE=./user.info
  4. for USER in $USER_LIST;do
  5. if ! id $USER &>/dev/null; then
  6. PASS=$(echo $RANDOM |md5sum |cut -c 1-8)
  7. useradd $USER
  8. echo $PASS | passwd --stdin $USER &>/dev/null
  9. echo "$USER $PASS" >> $USER_FILE
  10. echo "$USER User create successful."
  11. else
  12. echo "$USER User already exists!"
  13. fi
  14. done

3、一键查看服务器利用率

  1. #!/bin/bash
  2. function cpu(){
  3. util=$(vmstat | awk '{if(NR==3)print $13+$14}')
  4. iowait=$(vmstat | awk '{if(NR==3)print $16}')
  5. echo "CPU -使用率:${util}% ,等待磁盘IO相应使用率:${iowait}:${iowait}%"
  6. }
  7. function memory (){
  8. total=`free -m |awk '{if(NR==2)printf "%.1f",$2/1024}'`
  9. used=`free -m |awk '{if(NR==2) printf "%.1f",($2-$NF)/1024}'`
  10. available=`free -m |awk '{if(NR==2) printf "%.1f",$NF/1024}'`
  11. echo "内存 - 总大小: ${total}G , 使用: ${used}G , 剩余: ${available}G"
  12. }
  13. disk(){
  14. fs=$(df -h |awk '/^\/dev/{print $1}')
  15. for p in $fs; do
  16. mounted=$(df -h |awk '$1=="'$p'"{print $NF}')
  17. size=$(df -h |awk '$1=="'$p'"{print $2}')
  18. used=$(df -h |awk '$1=="'$p'"{print $3}')
  19. used_percent=$(df -h |awk '$1=="'$p'"{print $5}')
  20. echo "硬盘 - 挂载点: $mounted , 总大小: $size , 使用: $used , 使用率: $used_percent"
  21. done
  22. }
  23. function tcp_status() {
  24. summary=$(ss -antp |awk '{status[$1]++}END{for(i in status) printf i":"status[i]" "}')
  25. echo "TCP连接状态 - $summary"
  26. }
  27. cpu
  28. memory
  29. disk
  30. tcp_status

4、找出占用CPU 内存过高的进程

  1. #!/bin/bash
  2. echo "-------------------CUP占用前10排序--------------------------------"
  3. ps -eo user,pid,pcpu,pmem,args --sort=-pcpu |head -n 10
  4. echo "-------------------内存占用前10排序--------------------------------"
  5. ps -eo user,pid,pcpu,pmem,args --sort=-pmem |head -n 10

5、查看网卡的实时流量

  1. #!/bin/bash
  2. eth0=$1
  3. echo -e "流量进入--流量传出 "
  4. while true; do
  5. old_in=$(cat /proc/net/dev |grep $eth0 |awk '{print $2}')
  6. old_out=$(cat /proc/net/dev |grep $eth0 |awk '{print $10}')
  7. sleep 1
  8. new_in=$(cat /proc/net/dev |grep $eth0 |awk '{print $2}')
  9. new_out=$(cat /proc/net/dev |grep $eth0 |awk '{print $10}')
  10. in=$(printf "%.1f%s" "$((($new_in-$old_in)/1024))" "KB/s")
  11. out=$(printf "%.1f%s" "$((($new_out-$old_out)/1024))" "KB/s")
  12. echo "$in $out"
  13. done

6、监控多台服务器磁盘利用率脚本

  1. #!/bin/bash
  2. HOST_INFO=host.info
  3. for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
  4. #取出用户名和端口
  5. USER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)
  6. PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)
  7. #创建临时文件,保存信息
  8. TMP_FILE=/tmp/disk.tmp
  9. #通过公钥登录获取主机磁盘信息
  10. ssh -p $PORT $USER@$IP 'df -h' > $TMP_FILE
  11. #分析磁盘占用空间
  12. USE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^\/dev/{print $NF,int($5)}' $TMP_FILE)
  13. #循环磁盘列表,进行判断
  14. for USE_RATE in $USE_RATE_LIST; do
  15. #取出等号(=)右边的值 挂载点名称
  16. PART_NAME=${USE_RATE%=*}
  17. #取出等号(=)左边的值 磁盘利用率
  18. USE_RATE=${USE_RATE#*=}
  19. #进行判断
  20. if [ $USE_RATE -ge 80 ]; then
  21. echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
  22. echo "服务器$IP的磁盘空间占用过高,请及时处理" | mail -s "空间不足警告" 你的qq@qq.com
  23. else
  24. echo "服务器$IP的$PART_NAME目录空间良好"
  25. fi
  26. done
  27. done

7、批量检测网站是否异常并邮件通知

  1. #!/bin/bash
  2. URL_LIST="www.baidu.com www.ctnrs.com www.der-matech.net.cn www.der-matech.com.cn www.der-matech.cn www.der-matech.top www.der-matech.org"
  3. for URL in $URL_LIST; do
  4. FAIL_COUNT=0
  5. for ((i=1;i<=3;i++)); do
  6. HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL)
  7. if [ $HTTP_CODE -eq 200 ]; then
  8. echo "$URL OK"
  9. break
  10. else
  11. echo "$URL retry $FAIL_COUNT"
  12. let FAIL_COUNT++
  13. fi
  14. done
  15. if [ $FAIL_COUNT -eq 3 ]; then
  16. echo "Warning: $URL Access failure!"
  17. echo "网站$URL坏掉,请及时处理" | mail -s "$URL网站高危" 1794748404@qq.com
  18. fi
  19. done

8、批量主机远程执行命令脚本

  1. #!/bin/bash
  2. COMMAND=$*
  3. HOST_INFO=host.info
  4. for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
  5. USER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)
  6. PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)
  7. PASS=$(awk -v ip=$IP 'ip==$1{print $4}' $HOST_INFO)
  8. expect -c "
  9. spawn ssh -p $PORT $USER@$IP
  10. expect {
  11. \"(yes/no)\" {send \"yes\r\"; exp_continue}
  12. \"password:\" {send \"$PASS\r\"; exp_continue}
  13. \"$USER@*\" {send \"$COMMAND\r exit\r\"; exp_continue}
  14. }
  15. "
  16. echo "-------------------"
  17. done

9、一键部署LNMP网站平台脚本

  1. #!/bin/bash
  2. NGINX_V=1.15.6
  3. PHP_V=5.6.36
  4. TMP_DIR=/tmp
  5. INSTALL_DIR=/usr/local
  6. PWD_C=$PWD
  7. echo
  8. echo -e "\tMenu\n"
  9. echo -e "1. Install Nginx"
  10. echo -e "2. Install PHP"
  11. echo -e "3. Install MySQL"
  12. echo -e "4. Deploy LNMP"
  13. echo -e "9. Quit"
  14. function command_status_check() {
  15. if [ $? -ne 0 ]; then
  16. echo $1
  17. exit
  18. fi
  19. }
  20. function install_nginx() {
  21. cd $TMP_DIR
  22. yum install -y gcc gcc-c++ make openssl-devel pcre-devel wget
  23. wget http://nginx.org/download/nginx-${NGINX_V}.tar.gz
  24. tar zxf nginx-${NGINX_V}.tar.gz
  25. cd nginx-${NGINX_V}
  26. ./configure --prefix=$INSTALL_DIR/nginx \
  27. --with-http_ssl_module \
  28. --with-http_stub_status_module \
  29. --with-stream
  30. command_status_check "Nginx - 平台环境检查失败!"
  31. make -j 4
  32. command_status_check "Nginx - 编译失败!"
  33. make install
  34. command_status_check "Nginx - 安装失败!"
  35. mkdir -p $INSTALL_DIR/nginx/conf/vhost
  36. alias cp=cp ; cp -rf $PWD_C/nginx.conf $INSTALL_DIR/nginx/conf
  37. rm -rf $INSTALL_DIR/nginx/html/*
  38. echo "ok" > $INSTALL_DIR/nginx/html/status.html
  39. echo '<?php echo "ok"?>' > $INSTALL_DIR/nginx/html/status.php
  40. $INSTALL_DIR/nginx/sbin/nginx
  41. command_status_check "Nginx - 启动失败!"
  42. }
  43. function install_php() {
  44. cd $TMP_DIR
  45. yum install -y gcc gcc-c++ make gd-devel libxml2-devel \
  46. libcurl-devel libjpeg-devel libpng-devel openssl-devel \
  47. libmcrypt-devel libxslt-devel libtidy-devel
  48. wget http://docs.php.net/distributions/php-${PHP_V}.tar.gz
  49. tar zxf php-${PHP_V}.tar.gz
  50. cd php-${PHP_V}
  51. ./configure --prefix=$INSTALL_DIR/php \
  52. --with-config-file-path=$INSTALL_DIR/php/etc \
  53. --enable-fpm --enable-opcache \
  54. --with-mysql --with-mysqli --with-pdo-mysql \
  55. --with-openssl --with-zlib --with-curl --with-gd \
  56. --with-jpeg-dir --with-png-dir --with-freetype-dir \
  57. --enable-mbstring --enable-hash
  58. command_status_check "PHP - 平台环境检查失败!"
  59. make -j 4
  60. command_status_check "PHP - 编译失败!"
  61. make install
  62. command_status_check "PHP - 安装失败!"
  63. cp php.ini-production $INSTALL_DIR/php/etc/php.ini
  64. cp sapi/fpm/php-fpm.conf $INSTALL_DIR/php/etc/php-fpm.conf
  65. cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
  66. chmod +x /etc/init.d/php-fpm
  67. /etc/init.d/php-fpm start
  68. command_status_check "PHP - 启动失败!"
  69. }
  70. read -p "请输入编号:" number
  71. case $number in
  72. 1)
  73. install_nginx;;
  74. 2)
  75. install_php;;
  76. 3)
  77. install_mysql;;
  78. 4)
  79. install_nginx
  80. install_php
  81. ;;
  82. 9)
  83. exit;;
  84. esac

10、监控MySQL主从同步状态是否异常脚本

  1. #!/bin/bash
  2. HOST=localhost
  3. USER=root
  4. PASSWD=123.com
  5. IO_SQL_STATUS=$(mysql -h$HOST -u$USER -p$PASSWD -e 'show slave status\G' 2>/dev/null |awk '/Slave_.*_Running:/{print $1$2}')
  6. for i in $IO_SQL_STATUS; do
  7. THREAD_STATUS_NAME=${i%:*}
  8. THREAD_STATUS=${i#*:}
  9. if [ "$THREAD_STATUS" != "Yes" ]; then
  10. echo "Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!" |mail -s "Master-Slave Staus" xxx@163.com
  11. fi
  12. done

11、MySql数据库备份脚本

分库备份

mysqldump -uroot -pxxx -B A > A.sql

  1. #!/bin/bash
  2. DATE=$(date +%F_%H-%M-%S)
  3. HOST=localhost
  4. USER=backup
  5. PASS=123.com
  6. BACKUP_DIR=/data/db_backup
  7. 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")
  8. for DB in $DB_LIST; do
  9. BACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sql
  10. if ! mysqldump -h$HOST -u$USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null; then
  11. echo "$BACKUP_NAME 备份失败!"
  12. fi
  13. done

分表备份

mysqldump -uroot -pxxx -A t > t.sql

  1. #!/bin/bash
  2. DATE=$(date +%F_%H-%M-%S)
  3. HOST=localhost
  4. USER=backup
  5. PASS=123.com
  6. BACKUP_DIR=/data/db_backup
  7. 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")
  8. for DB in $DB_LIST; do
  9. BACKUP_DB_DIR=$BACKUP_DIR/${DB}_${DATE}
  10. [ ! -d $BACKUP_DB_DIR ] && mkdir -p $BACKUP_DB_DIR &>/dev/null
  11. TABLE_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "use $DB;show tables;" 2>/dev/null)
  12. for TABLE in $TABLE_LIST; do
  13. BACKUP_NAME=$BACKUP_DB_DIR/${TABLE}.sql
  14. if ! mysqldump -h$HOST -u$USER -p$PASS $DB $TABLE > $BACKUP_NAME 2>/dev/null; then
  15. echo "$BACKUP_NAME 备份失败!"
  16. fi
  17. done
  18. done

12、Nginx访问日志分析

  1. #!/bin/bash
  2. # 日志格式: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"
  3. LOG_FILE=$1
  4. echo "统计访问最多的10个IP"
  5. awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10
  6. echo "----------------------"
  7. echo "统计时间段访问最多的IP"
  8. 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
  9. echo "----------------------"
  10. echo "统计访问最多的10个页面"
  11. 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
  12. echo "----------------------"
  13. echo "统计访问页面状态码数量"
  14. awk '{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}' $LOG_FILE |sort -k3 -nr

13、Nginx访问日志自动按天(周、月)切割

  1. #!/bin/bash
  2. #nginx日志目录
  3. LOG_DIR=/www/server/nginx/logs
  4. #获取到上一天的时间
  5. YESTERDAY_TIME=$(date -d "yesterday" +%F)
  6. #归档日志取时间
  7. LOG_MONTH_DIR=$LOG_DIR/$(date +"%Y-%m")
  8. #归档日志的名称
  9. LOG_FILE_LIST="access.log"
  10. for LOG_FILE in $LOG_FILE_LIST; do
  11. [ ! -d $LOG_MONTH_DIR ] && mkdir -p $LOG_MONTH_DIR
  12. mv $LOG_DIR/$LOG_FILE $LOG_MONTH_DIR/${LOG_FILE}_${YESTERDAY_TIME}
  13. done
  14. kill -USR1 $(cat $LOG_DIR/nginx.pid)

14、自动发布Java项目(Tomcat)

  1. #!/bin/bash
  2. DATE=$(date +%F_%T)
  3. TOMCAT_NAME=$1
  4. TOMCAT_DIR=/usr/local/$TOMCAT_NAME
  5. ROOT=$TOMCAT_DIR/webapps/ROOT
  6. BACKUP_DIR=/data/backup
  7. WORK_DIR=/tmp
  8. PROJECT_NAME=tomcat-java-demo
  9. # 拉取代码
  10. cd $WORK_DIR
  11. if [ ! -d $PROJECT_NAME ]; then
  12. git clone https://github.com/lizhenliang/tomcat-java-demo
  13. cd $PROJECT_NAME
  14. else
  15. cd $PROJECT_NAME
  16. git pull
  17. fi
  18. # 构建
  19. mvn clean package -Dmaven.test.skip=true
  20. if [ $? -ne 0 ]; then
  21. echo "maven build failure!"
  22. exit 1
  23. fi
  24. # 部署
  25. TOMCAT_PID=$(ps -ef |grep "$TOMCAT_NAME" |egrep -v "grep|$$" |awk 'NR==1{print $2}')
  26. [ -n "$TOMCAT_PID" ] && kill -9 $TOMCAT_PID
  27. [ -d $ROOT ] && mv $ROOT $BACKUP_DIR/${TOMCAT_NAME}_ROOT$DATE
  28. unzip $WORK_DIR/$PROJECT_NAME/target/*.war -d $ROOT
  29. $TOMCAT_DIR/bin/startup.sh

15、自动发布PHP项目

  1. #!/bin/bash
  2. DATE=$(date +%F_%T)
  3. WWWROOT=/usr/local/nginx/html/$1
  4. BACKUP_DIR=/data/backup
  5. WORK_DIR=/tmp
  6. PROJECT_NAME=php-demo
  7. # 拉取代码
  8. cd $WORK_DIR
  9. if [ ! -d $PROJECT_NAME ]; then
  10. git clone https://github.com/lizhenliang/php-demo
  11. cd $PROJECT_NAME
  12. else
  13. cd $PROJECT_NAME
  14. git pull
  15. fi
  16. # 部署
  17. if [ ! -d $WWWROOT ]; then
  18. mkdir -p $WWWROOT
  19. rsync -avz --exclude=.git $WORK_DIR/$PROJECT_NAME/* $WWWROOT
  20. else
  21. rsync -avz --exclude=.git $WORK_DIR/$PROJECT_NAME/* $WWWROOT
  22. fi

16、DOS攻击防范(自动屏蔽攻击IP)

  1. #!/bin/bash
  2. DATE=$(date +%d/%b/%Y:%H:%M)
  3. #nginx日志
  4. LOG_FILE=/usr/local/nginx/logs/demo2.access.log
  5. #分析ip的访问情况
  6. ABNORMAL_IP=$(tail -n5000 $LOG_FILE |grep $DATE |awk '{a[$1]++}END{for(i in a)if(a[i]>10)print i}')
  7. for IP in $ABNORMAL_IP; do
  8. if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
  9. iptables -I INPUT -s $IP -j DROP
  10. echo "$(date +'%F_%T') $IP" >> /tmp/drop_ip.log
  11. fi
  12. done

17、目录入侵检测与告警

  1. #!/bin/bash
  2. MON_DIR=/opt
  3. inotifywait -mqr --format %f -e create $MON_DIR |\
  4. while read files; do
  5. #同步文件
  6. rsync -avz /opt /tmp/opt
  7. #检测文件是否被修改
  8. #echo "$(date +'%F %T') create $files" | mail -s "dir monitor" xxx@163.com
  9. done