连续复制
一键复制
一键打包

get_page_time.bash

#!/bin/bash
begin_time=`date +%s%N`
curl  -s  -H 'Host: bbs.iammecn.com' $1 >/tmp/tmp
end_time=`date +%s%N`
let time1="$end_time"-"$begin_time"
let time1="time1/1000000"
begin_time=`date +%s%N`
curl  -s  -H 'Host: www.iammecn.com' $1 >/tmp/tmp
end_time=`date +%s%N`
let time2="$end_time"-"$begin_time"
let time2="time2/1000000"
printf misstime:$time1
printf " "hittime:$time2

log.sh

#! /bin/bash

echo "本脚本放到日志目录下"
echo "日志的日期 两位数"
read LOG_TIME
echo "生成日志名称 随便去一个名称"
read LOG_NAME
echo "输入需要拉取日志时间 eg:0911-0944"
read TIME
echo "$TIME" > source
HOUR= cut -c 1,2 source
MIN= cut -c 3,4 source
TOHOUR= cut -c 6,7 source
TOMIN= cut -c 8,9 source

M=`date "+%m"`
echo $MONTH
D=`date "+%d"`
STIME=$HOUR:$MIN:00
DTIME=$TOHOUR:$TOMIN:00
if [ "$LOG_TIME" == "$D" ];then
    echo "当天"
    cat server.log | awk '$1 >= ${STIME} && $1 <= ${DTIME}' > "$LOG_NAME"_"$LOG_TIME"_"$TIME".log
echo "    cat server.log | awk '$1 >= "$HOUR':'$MIN':'00" && $1 <="$TOHOUR':'$TOMIN':'00"' > {"$TIME}".log"
else
    echo "不是当天"
    cat server.log.2017-$M-$LOG_TIME | awk '$1 >= "$HOUR':'$MIN':'00" && $1 <="$TOHOUR':'$TOMIN':'00"' > "$LOG_NAME"_"$LOG_TIME"_"$TIME".log
fi

zip "$LOG_NAME"_"$LOG_TIME"_"$TIME".zip  "$LOG_NAME"_"$LOG_TIME"_"$TIME".log

ping-time.sh

#! /bin/bash

ping 192.168.13.111 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime())}' >>/mnt/106-111.log
ping 192.168.13.108 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime())}' >>/mnt/106-108.log
ping 192.168.13.109 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime())}' >>/mnt/106-109.log
ping 192.168.13.1 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime())}' >>/mnt/106-1.log
ping 192.168.13.254 | awk '{ print $0"\t" strftime("%Y-%m-%d %H:%M:%S",systime())}' >>/mnt/106-254.log

redis_outfile.sh

#! /bin/bash

REDIS_HOST=200.200.6.17
REDIS_PORT=6379
REDIS_DB=1


KEYNAME=*
KEYFILE=key.txt
echo "KEYS *" | redis-cli -h $REDIS_HOST  > $KEYFILE
VALUEFILE=value.txt

for key in `cat $KEYFILE`
do
echo "get $key" | redis-cli -h $REDIS_HOST >> $VALUEFILE
done
paste $KEYFILE $VALUEFILE >key_value.txt    

run.sh

#!/bin/bash
#export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
PROJPATH=$(cd `dirname $0` && pwd)
EXENAME=${PROJPATH}/app.py
PORTBASE=8081

flag_stop=0
flag_start=0
inst_id=0
if [ $# -lt 1 ]; then
  echo "usage: $0 [start|stop|restart|status|terminate] [id]"
  exit 1;
else
  if [ "$1" == 'stop' ] ; then
    flag_stop=15
  elif [ "$1" == 'start' ] ; then
    flag_start=1
  elif [ "$1" == 'restart' ] ; then
    flag_stop=15
    flag_start=1
  elif [ "$1" == 'terminate' ] ; then
    flag_stop=9
  elif [ "$1" != 'status' ] ; then
    echo "Bad command for $0: $1" && exit 1
  fi
  if [ $# -ge 2 ]; then
    inst_id=$2
  fi
fi

# --logging=debug|info|warning|error|none
let "port=${PORTBASE}+${inst_id}"
EXEOPTS="--port=$port --workers=1"

# make the configuring path happy:
cd $(dirname "${EXENAME}")

function do_prepare_exe()
{
  if [ ! -f $EXENAME ]; then
    echo "ERROR: $EXENAME is not existing" && exit 1
  fi
  ulimit -c 409600 >/dev/null 2>&1
  ulimit -n 65535 >/dev/null 2>&1
  mkdir -p "${PROJPATH}/logs"
  chmod +rw "${PROJPATH}/logs" -R >/dev/null 2>&1
}

pid=
pidnum=

function get_pid_etc()
{
  pid=`ps -ef | grep "${EXENAME} --id=${inst_id}" | grep -v "\<grep\>" | grep -v "\<vim*\>" | awk '{print $2}'`
  pidnum=`echo $pid | wc | awk '{print $2}'`
}

if [ ${flag_stop} -eq 0 -a ${flag_start} -eq 0 ] ; then
  get_pid_etc
  test $pidnum -ne 0 && echo "running" || echo "stopped"
  exit 0
fi

if [ ${flag_stop} -ne 0 ] ; then
  get_pid_etc
  if [ $pidnum -ne 0 ]; then
    kill -${flag_stop} $pid >/dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "Cannot kill, stop ${EXENAME} failed." && exit 1
    fi
    echo -n "${EXENAME} is stopping (signal=${flag_stop}, pid=$pid)."
    while sleep 1
          get_pid_etc
          [ $pidnum -ne 0 ]
    do
      echo -n "."
    done
    echo " done."
  else
    echo "${EXENAME} is not running, nothing done!"
  fi
fi


if [ ${flag_start} -ne 0 ] ; then
  get_pid_etc
  if [ $pidnum -ne 0 ]; then
    echo "${EXENAME} is always running, nothing done!"
  else
    do_prepare_exe
    nohup python3.6 ${EXENAME} --id=${inst_id} ${EXEOPTS} >> ${PROJPATH}/logs/console.${inst_id}.`date +"%Y%m%d"`.log 2>&1 &
    echo -n "${EXENAME} is starting." && \
        sleep 1 && echo -n "." && \
        sleep 1 && echo -n "." && \
        sleep 1 && get_pid_etc
    if [ $pidnum -eq 0 ]; then
       echo " failed." && exit 1
    else
       echo " ok (pid=$pid)." && exit 0
    fi
  fi
fi

数据库操作

bak.sh

#! /bin/bash
# auto_bak_table.sh
#gps 为含有GPS的表
#nosps 没有包含GPS的表
#tables 指定数据库中的表
#恢复数据目录
DIR_RES=/home/barron
USER=root
PW=123
file=`date +%Y%m%d`
DATABASE=td_busonline845
if [ ! -d "$DIR_RES/$file/log"  ];then
    mkdir -p $file
fi
rm -rf $DIR_RES/gps $DIR_RES/nogps
mysql -u$USER -p$PW >tables.txt  <<EOF
use td_busonline845;
show tables;
quit
EOF
sed -i '1d' tables.txt
echo "数据备份中..."
for sql in `cat tables.txt`
do
    if [[ $sql =~ "gps" ]];then
    echo  "$sql" >> gps
    else
    echo  "$sql" >> nogps
    mysqldump  -u$USER -p$PW  $DATABASE  "$sql" >$file/$sql.sql
    fi    
done
mv gps $DIR_RES/$file
mv nogps $DIR_RES/$file
cp  restore.sh  $DIR_RES/$file
rm -rf tables.txt
tar -zcvf $file.tar.gz $file
rm -rf $file
echo "备份完成!"

bak1.sh

#! /bin/bash
# auto_bak_table.sh
#gps 为含有GPS的表
#nosps 没有包含GPS的表
#tables 指定数据库中的表
#恢复数据目录
DIR_RES=/home/barron
USER=root
PW=123
file=`date +%Y%m%d`"disp"
DATABASE=td_busonlinedisp845
TABLE1=dh_busoperatrecord
TABLE2=dh_busoperatrecordt
if [ ! -d "$DIR_RES/$file"  ];then
    mkdir $file
fi    
mysqldump  -u$USER -p$PW  $DATABASE  $TABLE1 $TABLE2  >$file/busoperatrecord.sql
tar -zcvf $file.tar.gz $file
rm -rf $file
echo "备份完成!"

drop.sh

#! /bin/bash
#description: 删除descritionlog表
#chkconfig:2345 80 90
# 删除description
USER=root
PASSWORD=123
DATABASE=td_busonlinedisp845
TABLE=dh_operationlog
echo "开始进入数据库删除表"
mysql -u$USER -p$PASSWORD <<EOF
use td_busonlinedisp845;
drop table dh_operationlog;
quit

EOF
echo "删除完成"

restore.sh

#! /bin/bash
# auto_bak_table.sh
#
echo "请输入要恢复数据库名称----此操作只是恢复非gps的表"
read database
echo "数据恢复中...."
for sql in `cat nogps`
do
    mysql  -uroot -p123  $database <$sql.sql
done
echo "数据恢复完成!"

日志文件夹监控

80.sh

#! /bin/bash

#Dir 表示需要监控的文件夹绝对路径
#Scale 表示指定的占比
#DiskUse 表示磁盘的使用率
#FileTime 当前时间
#/opt/disk.log 为脚本的日志文件
Dir=/boot
#Scale=40
FileTime=`date '+%Y-%m-%d %H':'%M':'%S'`
function diskuse()
{
    DiskUse=`df -Th|awk -F '[ |%]+' 'NR>1 {print $7"="$6}' | grep "$Dir" | awk -F "=" '{print $2}'`
    echo $DiskUse
}
function sort(){
cd $Dir
Dirlist=`ls -lrt |awk 'NR>1 {print $9}'`
for i in $Dirlist
do
echo "for"
DiskUse=`diskuse`
if [ "server.log" = "$i" ] || [ "upload-info.log" = "$i" ] || [[ "$DiskUse" < 40 ]];then
echo "循环退出"
continue
else
echo "del"
rm -rf $i
echo "$FileTime 删除文件名为:$i" >> /opt/disk.log
fi
done
}

function judge(){
DiskUse=`diskuse`
if [[ "$DiskUse" > 40 ]]; then
sort
echo "$DiskUse"
fi
}
function main(){
echo "$FileTime 检查磁盘" >> /opt/disk.log
judge
a=`diskuse`
echo "$a"
}
main

服务器监控

check_mysql.sh

#!/bin/bash  
MYSQL=/usr/bin/mysql  
MYSQL_HOST=localhost 
MYSQL_USER=root 
MYSQL_PASSWORD=123 
CHECK_TIME=3  
#mysql  is working MYSQL_OK is 1 , mysql down MYSQL_OK is 0  
MYSQL_OK=1 
function check_mysql_health (){  
$MYSQL -h $MYSQL_HOST -u $MYSQL_USER -p$MYSQL_PASSWORD -e "show status;" >/dev/null 2>&1  
if [ $? = 0 ] ;then  
     MYSQL_OK=1 
else  
     MYSQL_OK=0 
fi  
     return $MYSQL_OK  
}  
while [ $CHECK_TIME -ne 0 ]  
do  
     let "CHECK_TIME-=1"  ##(小提示这里我们采用的是let进行整数的运算当然您可以用expr,感觉let省去了$比较方便)
     check_mysql_health  
     if [ $MYSQL_OK = 1 ] ; then  
          CHECK_TIME=0 
          exit 0  
     fi  
 
     if [ $MYSQL_OK -eq 0 ] &&  [ $CHECK_TIME -eq 0 ]  
     then  
          /etc/init.d/keepalived stop  
     exit 1   
     fi  
     sleep 1  
done  

check_oneday.sh

#! /bin/bash

export TERM=linux   #防止脚本定时任务出错

count=3
ipaddr="200.200.6.17"
cpuUsage=`/usr/bin/top -bn 1 | awk -F '[ %]+' 'NR==3 {print $2}'`
#获取磁盘使用率
disktotal=`df -Th|awk -F '[ |%]+' 'NR>1 {print $7"="$6}'`
#获取内存情况
mem_total=`free -m | awk -F '[ :]+' 'NR==2{print $2}'`
mem_used=`free -m | awk -F '[ :]+' 'NR==3{print $3}'`
#统计内存使用率
mem_used_persent=`awk 'BEGIN{printf "%.0f\n",('$mem_used'/'$mem_total')*100}'`
#获取报警时间
now_time=`date '+%F %T'`
log_time=`date '+%Y-%m-%d %H-%M-%S'`
#获取网络情况
ping_status=`ping -c $count $ipaddr | awk 'NR==7 {print $4}'`
#统计丢包率
persent=$[count-ping_status]
ping_persent=`awk 'BEGIN{printf "%.0f\n",('$persent'/'$count')*100}'`
#获取本机IP地址
IP=`/sbin/ifconfig eth1 | awk '/inet addr/ {print $2}' | cut -d: -f2`
#规则判断
echo "$log_time IP地址:${IP} --> CPU使用率:${cpuUsage}% --> 内存使用率:${mem_used_persent}% --> 网络丢包率:  ${ping_persent}%" >> /home/sh/check.log

init_sh.bash


#! /bin/bash

user=root
passwd=
host=
port=
#初始化MySQL表create_table_sql="create table message ( id int not null auto_increment primary key, cpu varchar(100), mem varchar(100), disk varchar(100), net varchar(100), mysql varchar(100), nginx varchar(100), redis varchar(100), jboss varchar(100), mysql_log varchar(100), nginx_log varchar(100), jboss_log varchar(100), redis_log varchar(100), redis_mem varchar(100))"
mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD}  -D ${DBNAME} -e "${create_db_sql}"

#初始化计数
echo 1 > /var/monitor/mysql_log_num #文件标记
echo 1 > /var/monitor/jboss_log_num #文件标记
echo 1 > /var/monitor/nginx_log_num #文件标记
echo 1 > /var/monitor/log_num

init_sh.sh

#! /bin/bash

user=root
passwd=
host=
port=
#初始化MySQL表
create_table_sql="create table  IF NOT EXISTS message ( id int not null auto_increment primary key, cpu varchar(100), mem varchar(100), disk varchar(100), net varchar(100), mysql varchar(100), nginx varchar(100), redis varchar(100), jboss varchar(100), mysql_log varchar(100), nginx_log varchar(100), jboss_log varchar(100), redis_log varchar(100), redis_mem varchar(100))"
mysql -h${HOSTNAME}  -P${PORT}  -u${USERNAME} -p${PASSWORD}  -D ${DBNAME} -e "${create_db_sql}"

#初始化计数
Dir=/var/monitor/
if [ ! -d "$Dir" ]
then
mkdir -p "$Dir"
fi
echo 1 > /var/monitor/mysql_log_num #文件标记
echo 1 > /var/monitor/jboss_log_num #文件标记
echo 1 > /var/monitor/nginx_log_num #文件标记
echo 1 > /var/monitor/log_num


service_monitor.sh

#! /bin/bash

#服务器变量
#data_name="/dev/vda1"
#ping次数
count="3"
#日志路径

#邮箱地址
mail1="yuch@tongda.cc"
mail2="1281455504@qq.com"
mail3=""
#mysql账号密码
USER="root"
PASSWD="123"
database="monitor"
tablename="message"
#日志文件路径
monitor=/var/monitor/service_monitor.log
#对应服务器路径
jboss_log=  #真实日志路径
mysql_log=/var/lib/mysql/Test0.err
nginx_log=
mysql_log_num=/var/monitor/mysql_log_num #文件标记
jboss_log_num=/var/monitor/jboss_log_num #文件标记
nginx_log_num=/var/monitor/nginx_log_num #文件标记
log_num=/var/monitor/log_num
logfile=/tmp/logfile.log   #发邮件日志
send_monitor=/tmp/send_monitor.log #邮件截取日志
redis_config=  #redis配置文件路径
#获取信息
#获取cpu使用率
cpuUsage=`top -n 1 | awk -F '[ %]+' 'NR==3 {print $2}'`
#获取磁盘使用率
disktotal=`df -Th|awk -F '[ |%]+' 'NR>1 {print $7"="$6}'`


#获取内存情况
mem_total=`free -m | awk -F '[ :]+' 'NR==2{print $2}'`
mem_used=`free -m | awk -F '[ :]+' 'NR==3{print $3}'`
#统计内存使用率
mem_used_persent=`awk 'BEGIN{printf "%.0f\n",('$mem_used'/'$mem_total')*100}'`
#获取报警时间
now_time=`date '+%F %T'`
log_time=`date '+%Y-%m-%d %H-%M-%S'`
#获取网络情况
ping_status=`ping -c $count www.baidu.com|awk 'NR==7 {print $4}'`
#统计丢包率
persent=$[count-ping_status]
ping_persent=`awk 'BEGIN{printf "%.0f\n",('$persent'/'$count')*100}'`

#获取本机IP地址
IP=`ifconfig eth0 | awk '/inet addr/ {print $2}' | cut -d: -f2`
#规则判断
echo "$log_time IP地址:${IP} --> CPU使用率:${cpuUsage}% --> 内存使用率:${mem_used_persent}% --> 网络丢包率:  ${ping_persent}%" >> $monitor
#mysql 插入
# cpu mem disk net mysql nginx redis jboss mysql_log nginx_log jboss_log redis_log redis_mem
function insert_tables(){
    insert_table="insert into message  (cpu,mem) values ('10','20')"
    mysql -u$USER -p$PASSWD -D$database -e "${insert_table}"

}
#发送邮件
function send_mail(){
        #mail -s "监控报警" $mail1 < /tmp/monitor.log
    #mail -s "监控报警" $mail2 < /tmp/monitor.log
    cat $logfile | wc -l > $log_num
    num_l=`cat $log_num`
    sed -n ''$num_l',$'p $logfile >> $send_monitor

    #tail -n  4  /tmp/monitor.log > $send_monitor
    mail -s "监控报警" $mail1 < /tmp/send_monitor.log
    echo "$log_time !!!!!!!!发送告警邮件!!!!!!!"
}
#循环获取磁盘信息
function check_disk(){
    for i in $disktotal
    do
            diskname=`echo $i | awk -F'=' '{print $1}'`
            diskusage=`echo $i | awk -F'=' '{print $2}'`
            echo "$log_time 磁盘-->$diskname 使用率:  ${diskusage}% " >> $monitor
        if [ $diskusage -gt 80 ];then
            echo "$log_time 磁盘-->$diskname 使用率:  ${diskusage}% " >> $logfile
        insert_table="insert into message  (disk) values ('空间不足')"
        insert_tables
        send_mail
        echo "发送邮件 磁盘触发"
        fi
    done
}
####################
#检查中间件线程运行#
####################
function check_redis(){
    ps -fe | grep redis |grep -v grep
    if [ $? -ne 0 ]
    then
    echo "$log_time -->redis 未运行" >> $logfile
    echo "$log_time -->redis 未运行触发邮件" >> $monitor
    insert_table="insert into message  (redis) values ('未运行')"
    insert_tables
    send_mail
    else
    echo "$log_time -->redis 正常运行" >> $monitor
    fi

}

function check_mysql(){
    ps -fe | grep mysql |grep -v grep >> /dev/null

    if [ $? -ne 0 ]
    then
    echo "$log_time -->mysql 未运行" >> $logfile
    echo "$log_time -->mysql 未运行触发邮件" >> $monitor
    insert_table="insert into message  (mysql) values ('未运行')"
    insert_tables
    send_mail
    else
    echo "$log_time -->mysql 正常运行" >> $monitor
    fi
}

function check_nginx(){
    ps -fe | grep nginx |grep -v grep

    if [ $? -ne 0 ]
    then
    echo "$log_time -->nginx 未运行" >> $logfile
    echo "$log_time -->nginx 未运行触发邮件" >> $monitor
    insert_table="insert into message  (nginx) values ('未运行')"
    insert_tables
    send_mail
    else
    echo "$log_time -->nginx 正常运行" >> $monitor
    fi
}
##
#获取进程PID
function GetPID(){
    PsUser=$1
    PsName=$2
    pid=`ps -u $PsUser |grep $PsName|grep -v grep|grep -v vi|grep -v dbx\n |grep -v tail|grep -v start|grep -v stop |sed -n 1p |awk '{print $1}'`
    echo $pid
 }
#获取进程的内存使用量
function GetMem() {
        MEMUsage=`ps -o vsz -p $1|grep -v VSZ`
        (( MEMUsage /= 1000))
        echo $MEMUsage
}

##
#获取redis内存使用量
function check_redis_mem() {
    use_mem=$(redis-cli -h 127.0.0.1 info memory | grep used_memory_human: | awk -F ':' '{print $2}')
    max_mem=`cat $redis_config | grep  -E 'maxmemory [1-9]'|awk -F ' ' '{print $2}'`
    if [$use_mem > $max_mem]
    then
    echo "$log_time --> redis 运行内存不足 注意清理 使用:$use_mem 总共:$max_mem" >> $logfile
    echo "$log_time -->redis 内存不足 触发邮件" >> $monitor
    insert_table="insert into message  (redis) values ('空间不足')"
    insert_tables
    send_mail
    else
    echo "$log_time -->redis 内存使用正常 总共:$max_mem 使用:$use_mem "
fi
}

function auto_restore_redis(){
redis-cli -h 127.0.0.1 <<EOF
flushall

EOF


}
##########
#检查日志#
##########

function check_mysql_log(){
    cat $mysql_log | wc -l > $mysql_log_num
    num_m=`cat $mysql_log_num`
    my_error_num=`sed -n '$num_m,$'p $mysql_log | grep 'ERRO' | wc -l`
    if [ $my_error_num -ne 0 ]
    then
    echo "mysql 日志文件触发邮件"
    sed -n ''$num_m',$'p $mysql_log | grep -i 'ERRO' >> $logfile
    insert_table="insert into message  (mysql_log) values ('日志报警')"
    insert_tables
    send_mail
    fi
}
function check_nginx_log(){
    cat $nginx_log | wc -l > $nginx_log_num
    num_n=`cat $nginx_log_num`
    ng_error_num=`sed -n '$num_n,$'p $nginx_log | grep 'ERRO' | wc -l`
    if [ $ng_error_num -ne 0 ]
    then
    echo "nginx 日志文件触发邮件"
    sed -n ''$num_n',$'p $nginx_log | grep -i 'ERRO' >> $logfile
    insert_table="insert into message  (nginx_log) values ('日志报警')"
    insert_tables
    send_mail
    fi

}

#MySQL临时表空间  最大连接数
#function check_mysql_table(){
#}
function check_mysql_connect(){
    CRONNECTEB=`mysql -u$USER -p$PASSWD -e "show status;"|grep Threads_connected|awk '{print $2}'`
    echo "$log_time --> mysql 连接数:$CRONNECTEB  " >> $monitor

}
#状态数据写入数据库中
function create_table(){
create_table_sql="create table message ( id int not null auto_increment primary key, cpu varchar(100), mem varchar(100), disk varchar(100), net varchar(100), mysql varchar(100), nginx varchar(100), redis varchar(100), jboss varchar(100), mysql_log varchar(100), nginx_log varchar(100), jboss_log varchar(100), redis_log varchar(100), redis_mem varchar(100))"
}

function check(){

        if [[ "$cpuUsage" > 80 ]] || [[ "$mem_used_persent" > 80 ]] || [[ "$ping_persent" >  0 ]];then
        #if [[ "$cpuUsage" > 80 ]] || [[ "$mem_used_persent" > 80 ]];then
                echo "报警时间:${now_time}" >> $logfile
                echo "IP地址: ${IP} --> CPU使用率:${cpuUsage}% --> 内存使用率:${mem_used_persent}% --> 网络丢包率: ${ping_persen}" >> $logfile
                insert_table="insert into message  (cpu,mem,net) values ($cpuUsage,$mem_used_persent,$ping_persent)"
                insert_tables
                send_mail
        fi
}
function main(){
        check #检查基本状态 cpu 内存  网络
    check_disk #磁盘进程
    check_mysql #MySQL进程
    check_mysql_connect #MySQL连接数
#    check_nginx #nginx进程
#    check_redis #redis 进程
#    check_jboss_log #jboss日志
#    check_mysql_log #mysql 日志
#    check_nginx_log #nginx 日志

}
main

service_monitor_mysql.sh

#! /bin/bash

#服务器变量
#data_name="/dev/vda1"
#ping次数
count="3"
#日志路径

#邮箱地址
mail1="yuch@tongda.cc"
mail2="1281455504@qq.com"
mail3=""
#mysql账号密码
USER="root"
PASSWD="123"
database="monitor"
tablename="message"
#日志文件路径
monitor=/var/monitor/service_monitor.log
#对应服务器路径
jboss_log=  #真实日志路径
mysql_log=/var/lib/mysql/Test0.err
nginx_log=
mysql_log_num=/var/monitor/mysql_log_num #文件标记
jboss_log_num=/var/monitor/jboss_log_num #文件标记
nginx_log_num=/var/monitor/nginx_log_num #文件标记
log_num=/var/monitor/log_num
logfile=/tmp/logfile.log   #发邮件日志
send_monitor=/tmp/send_monitor.log #邮件截取日志
redis_config=  #redis配置文件路径
#获取信息
#获取cpu使用率
cpuUsage=`top -n 1 | awk -F '[ %]+' 'NR==3 {print $2}'`
#获取磁盘使用率
disktotal=`df -Th|awk -F '[ |%]+' 'NR>1 {print $7"="$6}'`


#获取内存情况
mem_total=`free -m | awk -F '[ :]+' 'NR==2{print $2}'`
mem_used=`free -m | awk -F '[ :]+' 'NR==3{print $3}'`
#统计内存使用率
mem_used_persent=`awk 'BEGIN{printf "%.0f\n",('$mem_used'/'$mem_total')*100}'`
#获取报警时间
now_time=`date '+%F %T'`
log_time=`date '+%Y-%m-%d %H-%M-%S'`
#获取网络情况
ping_status=`ping -c $count www.baidu.com|awk 'NR==7 {print $4}'`
#统计丢包率
persent=$[count-ping_status]
ping_persent=`awk 'BEGIN{printf "%.0f\n",('$persent'/'$count')*100}'`

#获取本机IP地址
IP=`ifconfig eth0 | awk '/inet addr/ {print $2}' | cut -d: -f2`
#规则判断
echo "$log_time IP地址:${IP} --> CPU使用率:${cpuUsage}% --> 内存使用率:${mem_used_persent}% --> 网络丢包率:  ${ping_persent}%" >> $monitor
#mysql 插入
# cpu mem disk net mysql nginx redis jboss mysql_log nginx_log jboss_log redis_log redis_mem
function insert_tables(){
    insert_table="insert into message  (cpu,mem) values ('10','20')"
    mysql -u$USER -p$PASSWD -D$database -e "${insert_table}"

}
#发送邮件
function send_mail(){
        #mail -s "监控报警" $mail1 < /tmp/monitor.log
    #mail -s "监控报警" $mail2 < /tmp/monitor.log
    cat $logfile | wc -l > $log_num
    num_l=`cat $log_num`
    sed -n ''$num_l',$'p $logfile >> $send_monitor

    #tail -n  4  /tmp/monitor.log > $send_monitor
    mail -s "监控报警" $mail1 < /tmp/send_monitor.log
    echo "$log_time !!!!!!!!发送告警邮件!!!!!!!"
}

function check_mysql(){
    ps -fe | grep mysql |grep -v grep >> /dev/null

    if [ $? -ne 0 ]
    then
    echo "$log_time -->mysql 未运行" >> $logfile
    echo "$log_time -->mysql 未运行触发邮件" >> $monitor
    insert_table="insert into message  (mysql) values ('未运行')"
    insert_tables
    send_mail
    else
    echo "$log_time -->mysql 正常运行" >> $monitor
    fi
}

##########
#检查日志#
##########

function check_mysql_log(){
    cat $mysql_log | wc -l > $mysql_log_num
    num_m=`cat $mysql_log_num`
    my_error_num=`sed -n '$num_m,$'p $mysql_log | grep 'ERRO' | wc -l`
    if [ $my_error_num -ne 0 ]
    then
    echo "mysql 日志文件触发邮件"
    sed -n ''$num_m',$'p $mysql_log | grep -i 'ERRO' >> $logfile
    insert_table="insert into message  (mysql_log) values ('日志报警')"
    insert_tables
    send_mail
    fi
}

#MySQL临时表空间  最大连接数
#function check_mysql_table(){
#}
function check_mysql_connect(){
    CRONNECTEB=`mysql -u$USER -p$PASSWD -e "show status;"|grep Threads_connected|awk '{print $2}'`
    echo "$log_time --> mysql 连接数:$CRONNECTEB  " >> $monitor

}
#状态数据写入数据库中
function create_table(){
create_table_sql="create table message ( id int not null auto_increment primary key, cpu varchar(100), mem varchar(100), disk varchar(100), net varchar(100), mysql varchar(100), nginx varchar(100), redis varchar(100), jboss varchar(100), mysql_log varchar(100), nginx_log varchar(100), jboss_log varchar(100), redis_log varchar(100), redis_mem varchar(100))"
}

function check(){

        if [[ "$cpuUsage" > 80 ]] || [[ "$mem_used_persent" > 80 ]] || [[ "$ping_persent" >  0 ]];then
        #if [[ "$cpuUsage" > 80 ]] || [[ "$mem_used_persent" > 80 ]];then
                echo "报警时间:${now_time}" >> $logfile
                echo "IP地址: ${IP} --> CPU使用率:${cpuUsage}% --> 内存使用率:${mem_used_persent}% --> 网络丢包率: ${ping_persen}" >> $logfile
                insert_table="insert into message  (cpu,mem,net) values ($cpuUsage,$mem_used_persent,$ping_persent)"
                insert_tables
                send_mail
        fi
}
function main(){
    check #检查基本状态 cpu 内存  网络
    check_disk #磁盘进程
    check_mysql #MySQL进程
    check_mysql_connect #MySQL连接数
}
main

批量改后缀

#!/bin/bash
oldext="dat"
newext="jpg"
dir=$(eval pwd)
for file in $(ls $dir | grep .$oldext)
        do
        name=$(ls $file | cut -d. -f1)
        mv $file ${name}.$newext
        done
echo "change dat=====>jpg done!"

批量重命名

#!/bin/bash
i=0
prefix="loginbg-"
for name in ./*.jpg; do
    echo "$name"
    let i=i+1
    echo "$i"
    mv $name ./$prefix$i.jpg
done

检查网络是否通畅

bash

#!/bin/bash
#检测网络链接畅通
function network()
{
    #超时时间
    local timeout=1
    #目标网站
    local target=www.baidu.com
    #获取响应状态码
    local ret_code=`curl -I -s --connect-timeout ${timeout} ${target} -w %{http_code} | tail -n1`
    if [ "x$ret_code" = "x200" ]; then
        #网络畅通
        return 1
    else
        #网络不畅通
        return 0
    fi
    return 0
}

network
if [ $? -eq 0 ];then
    reboot
    exit -1
fi

exit 0

sh

#!/bin/sh
host='www.baidu.com'
ping -c2 $host >>/dev/null
if [ $? -eq 0 ];then
    echo "network is ok,exit..."
else
    /etc/init.d/network restart
    echo "network is down,now restart network services"
#/etc/init.d/network restart
fi

免密码登录

ssh-keygen -t rsa #一路enter
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.91.135 #192.168.91.135 远程主机

目录

   ├── get_page_time.bash
   ├── log.sh
   ├── ping-time.sh
   ├── redis_outfile.sh
   └── 数据库操作
       ├── bak.sh
       ├── bak1.sh
       ├── drop.sh
       ├── restore.sh
   └── 日志文件夹监控
       ├── 80.sh
   └── 服务器监控
       ├── check_mysql.sh
       ├── check_oneday.sh
       ├── init_sh.bash
       ├── init_sh.sh
       ├── service_monitor.sh
       ├── service_monitor_mysql.sh