是时候来一波shell了
1 公司服务器是linux,你会写启停脚本吗???
easy
启动脚本
a=`ps -ef |grep abc|grep java|awk '{print $2}'`
echo $a
if [ ! $a ];then
nohup java -jar abc-node-2.0.0.jar >> nohup.txt &
echo "已启动,请查看日志"
tail -f nohup.txt
else
echo "已启动,请勿重复启动"
fi
停止脚本
pid=`ps -ef |grep abc|grep java|awk '{print $2}'`
echo "abc进程号为:$pid"
while :
do
a=`ps -ef |grep abc|grep java|awk '{print $2}'`
#echo $a
if [ ! $a ];then
echo "abc已停止"
break
else
kill -9 $a
fi
done
1.1 脚本写完了,发现没法执行,怎么办???
先赋权啊
chmod +x start.sh
chmod +x stop.sh
2 日志文件怎么看?好大啊,拉下来要半天
easy
三剑客登场 grep sed awk
2.1 文件太大,想看某一段时间的怎么办?
查询某个时间段的日志
sed -n '/2020-04-29 23:00:00/,/2020-04-29 23:10:00'p info.2020-04-29.log
2.2 文件太大,想要分成100MB一份怎么办?
easy
split -b 100M info.2020-04-29.log
2.3 想要查询日志中某个线程的日志怎么办?
easy
cat info.2020-04-29.log |grep 'task-35'
2.4 想要查询日志中某个关键字的前后10行怎么办?
easy
cat info.2020-04-29.log |grep -C10 'task-35'
2.5 日志中单行太长了,只想要耗时时间怎么办?
原日志:
easy
tail -f info.2020-05-08.log |grep 花费 |awk '{print $1 " " $NF}'
处理后:
3 docker容器挂了,没有发现啊,怎么办
需求:
- 监控所有name为test-xxx的docker容器
- 如果容器挂了,钉钉告警
- 如果某个容器已连续3次告警,暂停对该容器的告警5分钟(留5分钟时间给运维去启动容器)
webhook='https://oapi.dingtalk.com/robot/send?access_token=xxx'
function SendMsgToDingDing() {
curl $webhook -H 'Content-Type: application/json' -d "
{
'msgtype': 'text',
'text': {
'content': '告警!!!\n容器挂掉了,速去查看,容器列表:$containers'
},
'at': {
'atMobiles': [
'15628811xxx'
],
'isAtAll': false
}
}"
}
before_containers='null'
count=0
pending=10
sleep_count=1
while true ; do
current_second=`date +%S`
let current_second=10#${current_second}
#每10秒检测一次
if [ $((current_second % pending)) = 0 ];then
sleep 1s
containers=`docker ps -a|grep 'test-'|grep 'Exited'|awk '{print $NF}'`
#如果与上次报警的容器相同
if [ "$containers" == "$before_containers" ] ;then
#如果没达到3次
if [ $count -lt 3 ] ;then
#告警
SendMsgToDingDing
#次数+1
let count+=1
else
#已经告警三次,不再告警,等待5分钟
#如果已等了5分钟,告警次数归零、等待次数设为1
if [ $((pending * sleep_count)) == 300 ] ;then
let count=0
let sleep_count=1
#等待不足5分钟,等待次数+1
else
let sleep_count+=1
fi
fi
else
#如果与上次告警的容器不同,告警次数重置、等待次数重置
let count=0
let sleep_count=1
#如果有告警的容器,告警、保存本次告警的容器、告警次数+1
if [ ${#containers} -gt 0 ] ;then
before_containers=${containers}
SendMsgToDingDing
let count+=1
fi
fi
fi
done
4 机房断电了,如何快速启动所有docker呢?
脚本来了:
echo "====================================="
echo " 重启测试环境后端容器 "
echo "====================================="
a=`docker ps -a |grep 'test-'|awk '{print $NF}'`
echo $a
for i in $a ;
do
read -p "确定要重启$i? [y/n] " confirm
case $confirm in
[yY]*)
docker restart $i
;;
[nN]*)
echo "abort"
;;
*)
echo "abort"
;;
esac
done