在生产环境中,我们经常会写一些shell命令或者脚本来帮助我们的工作。本文分享几个我们最近使用的shell实用脚本的例子。感兴趣的朋友关注小编一起来看看吧。很多人认为shell脚本很简单,但其实小小的shell脚本却蕴藏着大智慧。别小看这几十行代码,其中夹杂着系统设计、代码规范、操作体验等细节。在构建自动化运维工作中,还是值得学习和学习的。编写脚本注意事项:开头加解释器:#!/bin/bash语法缩进,使用四个空格;添加更多评论。命名建议规则:变量名大写,局部变量小写,函数名小写,名字反映实际功能。默认变量是global,在函数中将变量local指定为局部变量,避免污染其他作用域。有两个命令可以帮助我调试脚本:set-e当执行非零时退出脚本,set-x打印执行过程。写脚本的时候一定要先测试再上线。1.备份当前日期文件#!/bin/bash#1个月前historyTime=$(date"+%Y-%m-%d%H"-d'1个月前')echo${historyTime}historyTimeStamp=$(date-d"$historyTime"+%s)echo${historyTimeStamp}#一周前$(date"+%Y-%m-%d%H"-d'7天前')#1月1日这个月的日期date_this_month=`date+%Y%m01`#一天前date_today=`date-d'1天前'+%Y%m%d`#一个小时前$(date"+%Y-%m-%d%H"-d'-1小时')2.DOS攻击防御(自动屏蔽攻击IP)#!/bin/bashDATE=$(date+%d/%b/%Y:%H:%M)#nginxLogLOG_FILE=/usr/local/nginx/logs/demo2.access.log#分析ip访问ABNORMAL_IP=$(tail-n5000$LOG_FILE|grep$DATE|awk'{a[$1]++}END{for(iina)if(a[i]>10)printi}')forIPin$ABNORMAL_IP;做if[$(iptables-vnL|grep-c"$IP")-eq0];然后iptables-IINPUT-s$IP-jDROPecho"$(date+'%F_%T')$IP">>/tmp/drop_ip.logfidone3,批量创建多少个用户并设置密码#!/bin/bashUSER_LIST=$@USER_FILE=./user.info用于$USER_LIST中的用户;如果!id$USER&>/dev/null;然后PASS=$(echo$RANDOM|md5sum|cut-c1-8)useradd$USERecho$PASS|密码--stdin$USER&>/dev/nullecho"$USER$PASS">>$USER_FILEecho"$USER用户创建成功。"elseecho"$USER用户已经存在!"fidone4、快速在Ubuntu20.04上架设LAMP服务器及WordPress博客详情见:https://www.linuxmi.com/ubuntu-20-04-lamp-wordpress.html#/bin/shinstall_dir="/var/www/html"#CreatingRandomWPDatabaseCredenitalsdb_name="wp`date+%s`"db_user=$db_namedb_password=`date|md5sum|cut-c'1-12'`sleep1mysqlrootpass=`date|md5sum|cut-c'1-12'`sleep1####安装https和mysqlapt的软件包-yinstallapache2apt-yinstallmysql-server####Starthttprm/var/www/html/index.htmlsystemctlenableapache2systemctlstartapache2####启动mysql并设置root密码systemctlenablemysqlsystemctlstartmysql/usr/bin/mysql-e"USEmysql;"/usr/bin/mysql-e"UPDATEuserSETPassword=PASSWORD($mysqlrootpass)WHEREuser='root';"/usr/bin/mysql-e"FLUSHPRIVILEGES;"touch/root/.my.cnfchmod640/root/.my.cnfecho"[客户端]">>/root/.my.cnfecho"user=root">>/root/.my.cnfecho"password="$mysqlrootpass>>/root/.my.cnf####InstallPHPapt-yinstallphpapt-yphp-mysqlapt-yphp-gdsed-i'0,/AllowOverride\无/!{0,/AllowOverride\None/s/AllowOverride\None/AllowOverride\All/}'/etc/apache2/apache2.conf#Allowhtaccessusagesystemctlrestartapache2####DownloadandextractlatestWordPressPackageiftest-f/tmp/latest.tar.gzthenecho"WP已经下载。"elseecho"正在下载WordPress"cd/tmp/&&wget"http://wordpress.org/latest.tar.gz";fi/bin/tar-C$install_dir-zxf/tmp/latest.tar.gz--strip-components=1chownwww-data:$install_dir-R####创建WP-config并设置数据库凭据/bin/mv$install_dir/wp-config-sample.php$install_dir/wp-config.php/bin/sed-i"s/database_name_here/$db_name/g"$install_dir/wp-config.php/bin/sed-i"s/username_here/$db_user/g"$install_dir/wp-config.php/bin/sed-i"s/password_here/$db_password/g"$install_dir/wp-config.phpcat<>$install_dir/wp-config.phpdefine('FS_METHOD','direct');EOFcat<>$install_dir/.htaccess#开始WordPressRewriteEngineOnRewriteBase/RewriteRule^index.php$–[L]RewriteCond%{REQUEST_FILENAME}!-fRewriteCond%{REQUEST_FILENAME}!-dRewriteRule。/index.php[L]#ENDWordPressEOFchownwww-data:$install_dir-R#####设置WPSaltsgrep-A50'table_prefix'$install_dir/wp-config.php>/tmp/wp-tmp-config/bin/sed-i'/**#@/,/$p/d'$install_dir/wp-config.php/usr/bin/lynx--dump-width200https://api.wordpress。org/secret-key/1.1/salt/>>$install_dir/wp-config.php/bin/cat/tmp/wp-tmp-config>>$install_dir/wp-config.php&&rm/tmp/wp-tmp-config-f/usr/bin/mysql-uroot-e"CREATEDATABASE$db_name"/usr/bin/mysql-uroot-e"CREATEUSER'$db_name'@'localhost'使用mysql_native_passwordBY'$db_password标识';"/usr/bin/mysql-uroot-e"GRANTALLPRIVILEGESON$db_name.*TO'$db_user'@'localhost';"######Displaygeneratedpasswordstologfile.echo"数据库名:"$db_nameecho"数据库用户:"$db_userecho"数据库密码:"$db_passwordecho"mysqlroot密码:"$mysqlrootpass5,每天自动备份mysql数据库#!/bin/sh#数据库infoDB_USER="batsing"DB_PASS="batsingpw"DB_HOST="localhost"DB_NAME="timepusher"#一些变量BIN_DIR="/usr/bin"#mysqlbin路径BCK_DIR="/mnt/mysqlBackup"#备份文件目录DATE=`date+%F`#TODO#/usr/bin/mysqldump--opt-ubatsing-pbatsingpw-hlocalhosttimepusher>/mnt/mysqlBackup/db_`date+%F`.sql$BIN_DIR/mysqldump--opt-u$DB_USER-p$DB_PASS-h$DB_HOST$DB_NAME>$BCK_DIR/db_$DATE.sql#恢复数据库#使用mysql-front导入前一天的*.sql文件恢复数据6.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"显示数据库;"2>/dev/null|egrep-v"数据库|information_schema|mysql|performance_schema|sys")对于$DB_LIST中的数据库;执行BACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sqlif!mysqldump-h$HOST-u$USER-p$PASS-B$DB>$BACKUP_NAME2>/dev/null;thenecho"$BACKUP_NAME备份失败!"fidone7、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"showdatabases;"2>/dev/null|egrep-v"Database|information_schema|mysql|performance_schema|sys")对于$DB_LIST中的数据库;执行BACKUP_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;showtables;"2>/dev/null)forTABLEin$TABLE_LIST;doBACKUP_NAME=$BACKUP_DB_DIR/${TABLE}.sqlif!mysqldump-h$HOST-u$USER-p$PASS$DB$TABLE>$BACKUP_NAME2>/dev/null;thenecho"$BACKUP_NAME备份失败!"fidonedone8、Nginx日志按要求截取#!/bin/bash#日志文件base_log_path='/usr/local/openresty/nginx/logs/access.log'base_error_path='/usr/local/openresty/nginx/logs中安装目录/error.log'#需要保存的目录位置log_path='/data_lytdev_dir/nginx/logs/'#获取月份log_month=$(date-dyesterday+"%Y%m")#获取前一天的日期(第二天凌晨备份,即保存的日志是当天的日志)log_day=$(date-dyesterday+"%d")#在指定位置创建文件夹mkdir-p$log_path/$log_month#将安装目录下的日志文件,移动到指定的存放位置log#复用信号控制切割日志#USR1表示nginx信号控制,切割日志kill-USR1`cat/usr/local/openresty/nginx/logs/nginx.pid`#每天凌晨1点切割日志*1***/usr/local/openresty/nginx/logs/log_rotate.sh9,生成10个随机数存入数组,求其最大值和最小值#!/bin/bashdeclare-iminmaxdeclare-anumsfor((i=0;i<10;i++));donums[$i]=$RANDOM[$i-eq0]&&min=${nums[0]}&&max=${nums[0]}&&continue[${nums[$i]}-gt$max]&&max=${nums[$i]}[${nums[$i]}-lt$min]&&min=${nums[$i]}doneecho"Allnumbersare${nums[*]}"echoMaxis$maxechoMinis$min10、#!/bin/bashNIC=$1echo-e"In------Out"虽然真实;做OLD_IN=$(awk'$0~"'$NIC'"{print$2}'/proc/net/dev)OLD_OUT=$(awk'$0~"'$NIC'"{print$10}'/proc/net/dev)sleep1NEW_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"sleep1done