1、服务器初始化
vim 1.sh
# 设置时区并同步时间
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
if ! crontab -l | grep ntpdate $>/dev/null ;then
(echo "* 1 * * * ntpdate -u time.windows.com >/dev/null 2>&1";crontab -l) | crontab
# echo "* 1 * * * ntpdate -u time.windows.com >/dev/null 2>&1" >>/var/spool/cron/root
fi
# 禁用linux
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
source /etc/bashrc
fi
#ssh超时时间
if ! grep "TMOUT=600" /etc/profile &>/dev/null;then
echo "export TMOUT=600" >> /etc/profile
source /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
2、发送告警邮件
# yum install -y mailx
# vim /etc/mail.rc
set [email protected] smtp=smtp.126.com
set [email protected] smtp-auth-password=007829liyang209
set smtp-auth=login
# echo "This is a test mail" | mail -s "Test" [email protected]
3、批量创建用户
# vim 3.sh
#!/bin/bash
for USER in user{1..10};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_info
echo "$USER User create sucessful."
else
echo "$USER User already exists!"
fi
done
4、一键查看服务器利用率
# vim 4.sh
#!/bin/bash
function cpu(){
util=$(vmstat | awk '{if(NR==3)print $13+$14}')
iowait=$(vmstat | awk '{if(NR==3)print $16}')
echo "CPU - 使用率: ${util}, IO等待使用率: ${iowait}"
}
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}')
avaliable=$(free -m | awk '{if(NR==2)printf "%.1f",$NF/1024}')
echo "内存-总大小: ${total}G , 已使用: ${used}G , 剩余: ${avaliable}G"
}
disk(){
fs=$(df -h | awk '/^\/dev/{print $1}')
for p in $fs; do
mounted=$(df -h | awk -v p=$p '$1==p{print $NF}')
size=$(df -h | awk -v p=$p '$1==p{print $2}')
used=$(df -h | awk -v p=$p '$1==p{print $3}')
used_percent=$(df -h | awk -v p=$p '$1==p{print $5}')
echo "硬盘 - 挂载点: ${mounted} , 总大小: $size , 已使用: $used , 使用率: $used_percent"
done
}
tcp_status(){
summary=$(netstat -antp | awk 'NR>2{print $0}' | awk '{a[$6]++}END{for (i in a)printf i":"a[i]" "}')
echo "TCP连接状态 - $summary"
}
cpu
memory
disk
tcp_status
5、找出CPU/内存占用率过高的进程
# vim 5.sh
#!/bin/bash
echo "--------------memory top 10-----------------"
ps -eo pid,pcpu,pmem,args --sort=-pmem | head -n 10
echo "--------------memory top 10-----------------"
ps -eo pid,pcpu,pmem,args --sort=-pcpu | head -n 10
6、查看网卡实时流量
# vim 6.sh
#!/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 $2}' /proc/net/dev)
sleep 1
NEW_IN=$( awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
NEW_OUT=$( awk '$0~"'$NIC'"{print $2}' /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
7、监控100台服务器磁盘利用率
# vim host.info
ip user port
# vim 7.sh
#!/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 [ $USER_RATE -ge 80 ]; then
echo -e "$IP \n Warning: $PART_NAME Partition usage $USE_RATE%!"
else
echo "YES"
fi
done
done
8、批量监控网站是否正常
# vim 8.sh
#!/bin/bash
URL_LIST="www.baidu.com www.abcd.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
let FAIL_COUNT++
echo "$URL retry $FAIL_COUNT"
fi
done
if [ $FAIL_COUNT -eq 3 ]; then
echo "Warning: $URL Access failure!"
fi
done
9、批量主机执行命令
# vim host.info
192.168.1.103 root 22 123456
192.168.1.104 root 22 123456
#192.168.1.105 root 22 123456
# vim 9.sh
#!/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
10、一键部署LNMP
# vim 10.sh
#!/bin/bash
NGINX_V=1.15.6
PHP_V=5.6.36
TMP_DIR=/tmp
INSTALL_DIR=/usr/local
PWD_C=$PWD
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"
function command_status_check(){
if [ $? -ne 0 ]; then
echo $1
exit
fi
}
function_install_nginx(){
cd $TMP_DIR
yum install -y gcc gcc-c++ make zlib openssl openssl-devel pcre pcre-devel wget
wget http://nginx.org/download/nginx-${NGINX_V}.tar.gz
tar zxvf 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
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 - 启动失败!"
}
function install_php(){
cd $TMP_DIR
yum install -y gcc gcc-c++ make db-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 zxvf 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 /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 $number in
1)
install_nginx;;
2)
install_php;;
3)
install_mysql;;
4)
install_nginx
install_php
;;
5)
exit;;
esac
11、监控Mysql主从同步状态是否异常
# vim 11.sh
#!/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!"
fi
done
12、mysql数据库备份
# vim 12-1.sh
#!/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 > $BACHUP_NAME 2>/dev/null; then
echo "$BACKUP_NAME 备份失败!"
fi
done
# vim 12-2.sh
#!/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
13、Nginx访问日志分析
- 访问最多的ip
- 访问最多的页面
- 访问页面状态码数量
- 根据时间段来访问最多的ip
- UV:用户访问次数
- PV:总页面访问次数
# vim 13.sh
#!/bin/bash
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 -k2 -rn
14、Nginx访问日志自动按天切割
# vim 14.sh
#!/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)
15、自动发布JAVA项目
# vim 15.sh
#!/bin/bash
DATE=$(date +%F_%T)
TOMCAT_NAME=$1
TOMCAT_DIR=/usr/local/$TOMCAT_NAME
ROOT=$TOMCAT_DIR/webapps/ROOT
BACKUP_DIR=/data/backup
WORK_DIR=/tmp
PROJECT_NAME=tomcat-java-demo
#拉取代码与构建
cd $WORK_DIR
if [ ! -d $PROJECT_NAME ]; then
git clone https://github.com/XXX/tomcat-java-demo
cd $PROJECT_NAME
else
cd $PROJECT_NAME
git pull
fi
mvn clean package -Dmaven.test.skip=true
if [ $? -ne 0 ]; then
echo "maven build failure!"
exit 1
fi
#部署
TOMCAT_PID=$(ps -ef | grep "$TOMCAT_NAME" | egrep -v "grep|$$" | awk 'NR==1{print $2}')
[ -n "$TOMCAT_PID" ] && kill -9 $TOMCAT_PID
[ -d $ROOT ] && mv $ROOT $BACKUP_DIR/${TOMCAT_NAME}_ROOT$DATE
unzip $WORK_DIR/$PROJECT_NAME/target/*.war -d $ROOT
$TOMCAT_DIR/bin/startup.sh
16、自动发布PHP项目
# vim 16.sh
#!/bin/bash
DATE=$(date +%F_%T)
WWWROOT=/usr/local/nginx/html/$1
BACKUP_DIR=/data/backup
WORK_DIR=/tmp
PROJECT_NAME=php-demo
#拉取代码
cd $WORK_DIR
if [ ! -d $PROJECT_NAME ]; then
git clone https://github.com/XXX/php-demo
cd $PROJECT_NAME
else
cd $PROJECT_NAME
git pull
fi
#部署
if [ ! -d $WWWROOT ]; then
mkdir -p $WWWROOT
rsync -avz --exclude=.git $WORK_DIR/$PROJECT_NAME/* $WWWROOT
else
rsync -avz --exclude=.git $WORK_DIR/$PROJECT_NAME/* $WWWROOT
fi