關註上方 浩道Linux ,回復 資料 ,即可獲取海量 L inux 、 Python 、 網路通訊、網路安全 等學習資料!
前言
大家好,這裏是 浩道Linux ,主要給大家分享 L inux 、 P ython 、 網路通訊、網路安全等 相關的IT知識平台。
轉眼又周五了!估計這又是打工人最期待的一天了,畢竟好多人這一天又可以摸魚了!但是當前大環境下,浩道建議大家還是保持著可以上班學習就多學習的態度,這樣你會過得更加充實。今天浩道跟大家分享十幾個經典的shell指令碼,大家可以在自己上班電腦上好好寫寫!
1、監控100台伺服器磁盤利用率指令碼
#!/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
2、監控MySQL主從同步狀態是否異常指令碼
#!/bin/bash
HOST=localhost
USER=root
PASSWD=123.com
IO_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; do
THREAD_STATUS_NAME=${i%:*}
THREAD_STATUS=${i#*:}
if [ "$THREAD_STATUS" != "Yes" ]; then
echo"Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!" |mail -s "Master-Slave Staus" [email protected]
fi
done
3、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
4、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
5、Dos攻擊防範(自動遮蔽攻擊IP)
#!/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
6、Linux系統發送告警指令碼
# yum install mailx
# vi /etc/mail.rc
setfrom=baojingtongzhi@163.com smtp=smtp.163.com
set smtp-auth-user=baojingtongzhi@163.com smtp-auth-password=123456
set smtp-auth=login
7、nginx 存取存取日誌按天切割
#!/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)
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=$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]}}' $LOG_FILE |sort -k3 -nr
9、檢視網卡即時流量指令碼
#!/bin/bash
NIC=$1
echo -e " In ------ Out"
whiletrue; 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
10、伺服器系統設定初始化指令碼
#/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 iftop iotp lrzsz -y
11、目錄檔變化監控和即時檔同步
#!/bin/bash
MON_DIR=/opt
inotifywait -mqr --format %f -e create $MON_DIR |\
whileread files; do
rsync -avz /opt /tmp/opt
#echo "$(date +'%F %T') create $files" | mail -s "dir monitor" [email protected]
done
12、批次建立100使用者並設定密碼指令碼
#!/bin/bash
DATE=$@
USER_FILE=user.txt
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
13、批次檢測網站是否異常指令碼
#!/bin/bash
URL_LIST="www.baidu.com www.ctnrs.com"
for URL in$URL_LIST; do
FAIL_COUNT=0
for ((i=1;i<=3;i++)); do
HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}"$URL)
if [ $HTTP_CODE -eq 200 ]; then
echo"$URL OK"
break
else
echo"$URL retry $FAIL_COUNT"
let FAIL_COUNT++
fi
done
if [ $FAIL_COUNT -eq 3 ]; then
echo"Warning: $URL Access failure!"
fi
done
14、批次主機遠端執行命令指令碼
#!/bin/bash
COMMAND=$*
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)
PASS=$(awk -v ip=$IP'ip==$1{print $4}'$HOST_INFO)
expect -c "
spawn ssh -p $PORT$USER@$IP
expect {
\"(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/bash
NGINX_V=1.15.6
PHP_V=5.6.36
TMP_DIR=/tmp
INSTALL_DIR=/usr/local
PWD_C=$PWD
echo
echo -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"
functioncommand_status_check() {
if [ $? -ne 0 ]; then
echo$1
exit
fi
}
functioninstall_nginx() {
cd$TMP_DIR
yum install -y gcc gcc-c++ make openssl-devel pcre-devel wget
wget http://nginx.org/download/nginx-${NGINX_V}.tar.gz
tar zxf nginx-${NGINX_V}.tar.gz
cd nginx-${NGINX_V}
./configure --prefix=$INSTALL_DIR/nginx \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-stream
command_status_check "Nginx - 平台環境檢查失敗!"
make -j 4
command_status_check "Nginx - 編譯失敗!"
make install
command_status_check "Nginx - 安裝失敗!"
mkdir -p $INSTALL_DIR/nginx/conf/vhost
alias cp=cp ; cp -rf $PWD_C/nginx.conf $INSTALL_DIR/nginx/conf
rm -rf $INSTALL_DIR/nginx/html/*
echo"ok" > $INSTALL_DIR/nginx/html/status.html
echo'<?php echo "ok"?>' > $INSTALL_DIR/nginx/html/status.php
$INSTALL_DIR/nginx/sbin/nginx
command_status_check "Nginx - 啟動失敗!"
}
functioninstall_php() {
cd$TMP_DIR
yum install -y gcc gcc-c++ make gd-devel libxml2-devel \
libcurl-devel libjpeg-devel libpng-devel openssl-devel \
libmcrypt-devel libxslt-devel libtidy-devel
wget http://docs.php.net/distributions/php-${PHP_V}.tar.gz
tar zxf php-${PHP_V}.tar.gz
cd 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-hash
command_status_check "PHP - 平台環境檢查失敗!"
make -j 4
command_status_check "PHP - 編譯失敗!"
make install
command_status_check "PHP - 安裝失敗!"
cp php.ini-production $INSTALL_DIR/php/etc/php.ini
cp sapi/fpm/php-fpm.conf $INSTALL_DIR/php/etc/php-fpm.conf
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
chmod +x /etc/init.d/php-fpm
/etc/init.d/php-fpm start
command_status_check "PHP - 啟動失敗!"
}
read -p "請輸入編號:" number
case$numberin
1)
install_nginx;;
2)
install_php;;
3)
install_mysql;;
4)
install_nginx
install_php
;;
9)
exit;;
esac
16、一鍵檢視伺服器資源利用率
#!/bin/bash
functioncpu() {
NUM=1
while [ $NUM -le 3 ]; do
util=`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 1
done
}
functionmemory() {
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"
}
functiondisk() {
fs=$(df -h |awk '/^\/dev/{print $1}')
for p in$fs; do
mounted=$(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
}
functiontcp_status() {
summary=$(ss -antp |awk '{status[$1]++}END{for(i in status) printf i":"status[i]" "}')
echo"TCP連線狀態 - $summary"
}
cpu
memory
disk
tcp_status
17、找出占用CPU 記憶體過高的行程指令碼
ps -eo user,pid,pcpu,pmem,args --sort=-pcpu |head -n 10
ps -eo user,pid,pcpu,pmem,args --sort=-pmem |head -n 10
更多精彩
關註公眾號 「 浩道Linux 」
浩道Linux ,專註於 Linux系統 的相關知識、 網路通訊 、 網路安全 、 Python相關 知識以及涵蓋IT行業相關技能的學習, 理論與實戰結合,真正讓你在學習工作中真正去用到所學。同時也會分享一些面試經驗,助你找到高薪offer,讓我們一起去學習,一起去進步,一起去漲薪!期待您的加入~~~ 關註回復「資料」可 免費獲取學習資料 (含有電子書籍、視訊等)。
喜歡的話,記得 點「贊」 和 「在看」 哦