shell1(一键lnmp、监控mysql主从、批量创建用户)
1、一键查看服务器资源利用率
#!/bin/bash function cpu() { 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 } 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}'` available=`free -m |awk '{if(NR==2) printf "%.1f",$NF/1024}'` echo "内存 - 总大小: ${total}G , 使用: ${used}G , 剩余: ${available}G" } function disk() { 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 } function tcp_status() { summary=$(ss -antp |awk '{status[$1]++}END{for(i in status) printf i":"status[i]" "}') echo "TCP连接状态 - $summary" } cpu memory disk tcp_status
2、简单系统工具
#!/bin/bash # system tools # v1 menu() { cat <<-EOF +-----------------------------------+ H:help of menu F:display disk partition D:filesystem mount M:memory info U:system load I: check to see if all hosts Q:exit +-----------------------------------+ EOF } mem_use() { mem_used=`free -m | grep "^Mem" | awk '{print $3}'` mem_total=`free -m | grep "^Mem" | awk '{print $2}'` mem_percent=$((mem_used*100/mem_total)) echo "${mem_percent}%" } ip_check() { for i in {2..20} do ip=192.168.8.$i ping -c 1 -w1 $ip &>/dev/null if [ $? -eq 0 ];then echo "$ip" >>/tmp/ip_online.txt else echo "$ip" >>/tmp/ip_notonline.txt fi done } while : do menu read -p "please choose:" action case "$action" in h|H) menu ;; f|F) fdisk -l disk_info=`df -h | grep "/$" | awk '{print $(NF-1)}'` echo "磁盘剩余空间为:$disk_info" ;; d|D) mount ;; m|M) free -m mem=$(mem_use) echo "剩余内存百分比为:$mem" ;; u|U) uptime ;; q|Q) break ;; I|i) ip_check if [ $? -eq 0 ];then echo "check finish" else echo "eheck fiald" fi ;; "") echo "请重新输入!!" ;; *) menu esac done
3、tomcat启动脚本
#!/bin/bash JAVA_HOME=/usr/local/jdk1.8/ JAVA_BIN=/usr/local/jdk1.8/bin JRE_HOME=/usr/local/jdk1.8/jre PATH=$PATH:/usr/local/jdk1.8/bin:/usr/local/jdk1.8/jre/bin CLASSPATH=/usr/local/jdk1.8/jre/lib:/usr/local/jdk1.8/lib:/usr/local/jdk1.8/jre/lib/charsets.jar TOMCAT_BIN=/usr/local/tomcat/bin RETVAL=0 prog="Tomcat" start() { echo "Starting $prog......" /bin/bash $TOMCAT_BIN/startup.sh RETVAL=$? return $RETVAL } stop() { echo "Stopping $prog......" /bin/bash $TOMCAT_BIN/shutdown.sh RETVAL=$? return $RETVAL } restart(){ echo "Restarting $prog......" stop start } case "$1" in start) start ;; stop) stop ;; restart) restart ;; *) echo $"Usage: $0 {start|stop|restart}" RETVAL=1 esac exit $RETVAL
自动发布 Java 项目(Tomcat)
#!/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 [url=https://github.com/lizhenliang/tomcat-java-demo]https://github.com/lizhenliang/tomcat-java-demo[/url] 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
4、统计内存使用
1 #!/bin/bash 2 count=0 3 # 这个循环会遍历出每个进程占用的内存大小 4 for i in `ps aux |awk '{print $6}' |grep -v 'RSS'` 5 do 6 # 将遍历出来的数字进行累加 7 count=$[$count+$i] 8 done 9 # 就得到所有进程占用内存大小的和了 10 echo "$count/kb" 11 12 或者 ps aux |grep -v 'RSS TTY' |awk '{sum=sum+$6};END{print sum}'
5、备份数据库
#!/bin/bash PATH=$PATHi:/usr/local/mysql/bin week=`date +%w` today=`date +d` passwd="123456" backdir="/data/mysql" r_backupIP="192.168.123.30::backup" exec 1>/var/log/mysqlbak.log 2>/var/log/mysqlbak.log echo "mysql backup begin at `date +%F %T`." # 本地备份 mysqldump -uroot -p$passwd --default-character-set=utf8 discuz >$backdir/$week.sql # 同步备份到远程机器 rsync -az $backdir/$week.sql $r_backupIP/$today.sql echo "mysql backup end at `date +%F %T`." 然后加入cron 0 3 * * * /bin/bash /usr/local/sbin/mysqlbak.sh
6、自动重启php-fpm服务
#!/bin/bash access_log="/data/log/access.log" N=10 while : do # 因为10秒大概产生300条日志记录 tail -n300 $access_log > /tmp/log # 拿出log中包含502的日志行数 n_502=`grep -c "502" /tmp/log` # 如果行数大于10 if [ $n_502 -ge $N ] then # 就记录一下系统状态 top -bn1 > /tmp/`date +%H%M%S`-top.log vmstat 1 5 > /tmp/`date +%H%M%S`-vm.log # 然后才重启服务,并把错误信息重定向 /etc/init.d/php-fpm restart 2> /dev/null # 重启php-fpm服务后,应先暂缓1分钟,而后继续每隔10s检测一次 sleep(60) fi sleep(10) done
7、禁止恶意访问ip
#!/bin/bash ## 日志文件路径 log_file="/home/logs/client/access.log" ## 当前时间减一分钟的时间 d1=`date -d "-1 minute" +%H:%M` ## 当前时间的分钟段 d2=`date +%M` ## iptables命令所在的路径 ipt="/sbin/iptables" ## 用于存储访问日志里的ip ips="/tmp/ips.txt" ## 封ip block(){ ## 把日志文件中的ip过滤出来,去掉重复的ip,并统计ip的重复次数以及对ip进行排序,最后将结果写到一个文件中 grep "$d1:" $log_file |awk '{print $1}' |sort -n |uniq -c |sort -n > $ips ## 将文件里重复次数大于100的ip迭代出来 for ip in `awk '$1 > 100 {print $2}' $ips` do ## 通过防火墙规则对这些ip进行封禁 $ipt -I INPUT -p -tcp --dport 80 -s $ip -j REJECT ## 将已经封禁的ip输出到一个文件里存储 echo "`date +%F-%T` $ip" >> /tmp/badip.txt done } ## 解封ip unblock(){ ## 将流量小于15的规则索引过滤出来 for i in `$ipt -nvL --line-number |grep '0.0.0.0/0' |awk '$2 < 15 {print $1}' |sort -nr` do ## 通过索引来删除规则 $ipt -D INPUT $i done ## 清空规则中的数据包计算器和字节计数器 $ipt -Z } ## 为整点或30分钟就是过了半个小时,就需要再进行分析 if [ $d2 == "00" ] || [ $d2 == "30" ] then unblock block else block fi
8、统计常用命令
sort /root/.bash_history |uniq -c |sort -nr |head -10 (-n 依照数值的大小排序 -r 以降序来排序)
9、系统-批量杀进程
ps aux |grep clearmem.sh |grep -v grep|awk '{print $2}'|xargs kill
10、监控mysql服务
假设,当前MySQL服务的root密码为123456,写脚本检测MySQL服务是否正常(比如,可以正常进入mysql执行show processlist),并检测一下当前的MySQL服务是主还是从,如果是从,请判断它的主从服务是否异常。如果是主,则不需要做什么。 #!/bin/bash Mysql_c="mysql -uroot -p123456" $Mysql_c -e "show processlist" >/tmp/mysql_pro.log 2>/tmp/mysql_log.err n=`wc -l /tmp/mysql_log.err|awk '{print $1}'` if [ $n -gt 0 ] then echo "mysql service sth wrong." else $Mysql_c -e "show slave status\G" >/tmp/mysql_s.log n1=`wc -l /tmp/mysql_s.log|awk '{print $1}'` if [ $n1 -gt 0 ] then y1=`grep 'Slave_IO_Running:' /tmp/mysql_s.log|awk -F : '{print $2}'|sed 's/ //g'` y2=`grep 'Slave_SQL_Running:' /tmp/mysql_s.log|awk -F : '{print $2}'|sed 's/ //g'` if [ $y1 == "Yes" ] && [ $y2 == "Yes" ] then echo "slave status good." else echo "slave down." fi fi fi
监控 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" [url=mailto:xxx@163.com]xxx@163.com[/url] fi done
11、抽签脚本
while : do read -p "Please input a name:" name if [ -f /work/test/1.log ];then bb=`cat /work/test/1.log | awk -F: '{print $1}' | grep "$name"` if [ "$bb" != "$name" ];then #名字不重复情况下 aa=`echo $RANDOM | awk -F "" '{print $2 $3}'` while : do dd=`cat /work/test/1.log | awk -F: '{print $2}' | grep "$aa"` if [ "$aa" == "$dd" ];then #数字已经存在情况下 echo "数字已存在." aa=`echo $RANDOM | awk -F "" '{print $2 $3}'` else break fi done echo "$name:$aa" | tee -a /work/test/1.log else aa=`cat /work/test/1.log | grep "$name" | awk -F: '{print $2}'` #名字重复 echo $aa echo "重复名字." fi else aa=`echo $RANDOM | awk -F "" '{print $2 $3}'` echo "$name:$aa" | tee -a /work/test/1.log fi done
12、检测脚本是否有误
#!/bin/bash sh -n $1 2>/tmp/err ($1指某一个具体脚本) if [ $? -eq "0" ] then echo "The script is OK." else cat /tmp/err read -p "Please inpupt Q/q to exit, or others to edit it by vim. " n if [ -z $n ] then vim $1 exit fi if [ $n == "q" -o $n == "Q" ] then exit else vim $1 exit fi fi
13、判断cpu厂商
#!/bin/bash m=`cat /proc/cpuinfo |grep vendor_id|awk -F":" '{print $2}'|tail -1` if [ $m == "GenuineIntel" ] then echo "cpu is 英特尔" elif [ $m == "AuthenticAMD" ] then echo "cpu is AMD" else echo "cpu is 非主流" fi
14、调用其他shell脚本
[root@zjz ~]# vim a.sh [root@zjz ~]# bash b.sh hello zhangjingzhi [root@zjz ~]# tail a.sh b.sh (对比) ==> a.sh <== hello () { echo hello zhangjingzhi } ==> b.sh <== . ./a.sh (调用a.sh,相对路径) hello
15、批量创建 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
16、批量检测网站是否异常脚本
#!/bin/bash URL_LIST="www.baidu.com [url=http://www.ctnrs.com]www.ctnrs.com[/url]" 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
17、一键部署 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" 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 openssl-devel pcre-devel wget wget [url=http://nginx.org/download/nginx-]http://nginx.org/download/nginx-[/url]${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 - 启动失败!" } function install_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 [url=http://docs.php.net/distributions/php-]http://docs.php.net/distributions/php-[/url]${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 $number in 1) install_nginx;; 2) install_php;; 3) install_mysql;; 4) install_nginx install_php ;; 9) exit;; esac
18、批量创建 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