10 个实用的 Shell 脚本!
杰哥的IT之旅
共 6767字,需浏览 14分钟
·
2022-02-12 03:21
在下方公众号后台回复:JGNB,可获取杰哥原创的 PDF 手册。
在生产环境中,我们会经常编写一些 Shell 命令或脚本帮我们的工作,本文分享了最近用到的几例 shell 实用脚本,感兴趣的朋友跟随杰哥一起看看吧。
很多人认为 Shell 脚本简单,但其实 Shell 小脚本却有大智慧。别小看几十行代码,它夹杂着系统设计、代码规范和操作经验等等细节,在建设自动化运维的工作中,还是很值得我们研究学习的。
编写脚本的注意事项:
开头加解释器:#!/bin/bash
语法缩进,使用四个空格;多加注释说明。
命名建议规则:变量名大写、局部变量小写,函数名小写,名字体现出实际作用。
默认变量是全局的,在函数中变量local指定为局部变量,避免污染其他作用域。
有两个命令能帮助我调试脚本:set -e 遇到执行非0时退出脚本,set-x 打印执行过程。
写脚本一定先测试再到生产上。
1、备份当前日期文件
#!/bin/bash
#一月前
historyTime=$(date "+%Y-%m-%d %H" -d '1 month ago')
echo ${historyTime}
historyTimeStamp=$(date -d "$historyTime" +%s)
echo ${historyTimeStamp}
#一周前
$(date "+%Y-%m-%d %H" -d '7 day ago')
#本月一月一日
date_this_month=`date +%Y%m01`
#一天前
date_today=`date -d '1 day ago' +%Y%m%d`
#一小时前
$(date "+%Y-%m-%d %H" -d '-1 hours')
2、DOS攻击防范(自动屏蔽攻击IP)
#!/bin/bash
DATE=$(date +%d/%b/%Y:%H:%M)
#nginx日志
LOG_FILE=/usr/local/nginx/logs/demo2.access.log
#分析ip的访问情况
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
3、批量创建多少个用户并设置密码
#!/bin/bash
USER_LIST=$@
USER_FILE=./user.info
for USER in $USER_LIST;do
if ! id $USER &>/dev/null; then
PASS=$(echo $RANDOM |md5sum |cut -c 1-8)
useradd $USER
echo $PASS | passwd --stdin $USER &>/dev/null
echo "$USER $PASS" >> $USER_FILE
echo "$USER User create successful."
else
echo "$USER User already exists!"
fi
done
4、快速在Ubuntu 20.04上架设LAMP服务器及WordPress博客
详情见:https://www.linuxmi.com/ubuntu-20-04-lamp-wordpress.html
#/bin/sh
install_dir="/var/www/html"
#Creating Random WP Database Credenitals
db_name="wp`date +%s`"
db_user=$db_name
db_password=`date |md5sum |cut -c '1-12'`
sleep 1
mysqlrootpass=`date |md5sum |cut -c '1-12'`
sleep 1
#### Install Packages for https and mysql
apt -y install apache2
apt -y install mysql-server
#### Start http
rm /var/www/html/index.html
systemctl enable apache2
systemctl start apache2
#### Start mysql and set root password
systemctl enable mysql
systemctl start mysql
/usr/bin/mysql -e "USE mysql;"
/usr/bin/mysql -e "UPDATE user SET Password=PASSWORD($mysqlrootpass) WHERE user='root';"
/usr/bin/mysql -e "FLUSH PRIVILEGES;"
touch /root/.my.cnf
chmod 640 /root/.my.cnf
echo "[client]">>/root/.my.cnf
echo "user=root">>/root/.my.cnf
echo "password="$mysqlrootpass>>/root/.my.cnf
####Install PHP
apt -y install php
apt -y php-mysql
apt -y php-gd
sed -i '0,/AllowOverride\ None/! {0,/AllowOverride\ None/ s/AllowOverride\ None/AllowOverride\ All/}' /etc/apache2/apache2.conf #Allow htaccess usage
systemctl restart apache2
####Download and extract latest WordPress Package
if test -f /tmp/latest.tar.gz
then
echo "WP is already downloaded."
else
echo "Downloading WordPress"
cd /tmp/ && wget "http://wordpress.org/latest.tar.gz";
fi
/bin/tar -C $install_dir -zxf /tmp/latest.tar.gz --strip-components=1
chown www-data: $install_dir -R
#### Create WP-config and set DB credentials
/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.php
cat << EOF >> $install_dir/wp-config.php
define('FS_METHOD', 'direct');
EOF
cat << EOF >> $install_dir/.htaccess
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
EOF
chown www-data: $install_dir -R
##### Set WP Salts
grep -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 -width 200 https://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 -u root -e "CREATE DATABASE $db_name"
/usr/bin/mysql -u root -e "CREATE USER '$db_name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$db_password';"
/usr/bin/mysql -u root -e "GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost';"
######Display generated passwords to log file.
echo "Database Name: " $db_name
echo "Database User: " $db_user
echo "Database Password: " $db_password
echo "Mysql root password: " $mysqlrootpass
5、每天自动备份 MySQL 数据库
#!/bin/sh
# Database info
DB_USER="batsing"
DB_PASS="batsingpw"
DB_HOST="localhost"
DB_NAME="timepusher"
# 一些变量
BIN_DIR="/usr/bin" #mysql bin路径
BCK_DIR="/mnt/mysqlBackup" #备份文件目录
DATE=`date +%F`
# TODO
# /usr/bin/mysqldump --opt -ubatsing -pbatsingpw -hlocalhost timepusher > /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/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
7、MySQL 数据库备份多循环
#!/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
8、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 -d yesterday +"%Y%m")
#获取前一天日期 (第二天凌晨备份,即保存的日志就是当天时间的日志)
log_day=$(date -d yesterday +"%d")
#在指定位置创建文件夹
mkdir -p $log_path/$log_month
#将安装目录下的日志文件,移动到指定存储位置
mv $base_log_path $log_path/$log_month/access_$log_day.log
mv $base_error_path $log_path/$log_month/error_$log_day.log
#再使用信号控制切割日志
#USR1 表示nginx信号控制,切割日志
kill -USR1 `cat /usr/local/openresty/nginx/logs/nginx.pid`
#每天凌晨1点切割日志
* 1 * * * /usr/local/openresty/nginx/logs/log_rotate.sh
9、生成10个随机数保存于数组中并找出其最大值和最小值
#!/bin/bash
declare -i min max
declare -a nums
for ((i=0;i<10;i++));do
nums[$i]=$RANDOM
[ $i -eq 0 ] && min=${nums[0]} && max=${nums[0]}&& continue
[ ${nums[$i]} -gt $max ] && max=${nums[$i]}
[ ${nums[$i]} -lt $min ] && min=${nums[$i]}
done
echo "All numbers are ${nums[*]}"
echo Max is $max
echo Min is $min
10、查看网卡实时流量
#!/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
来自:Linux迷
链接:https://www.linuxmi.com/shell-script-10.html
推荐阅读
超硬核!11 个非常实用的 Python 和 Shell 拿来就用脚本实例!
评论