第五部分shell项目一监控脚本
需求: 使用shell定制各种个性化告警工具,但需要统一化管理、规范化管理。
思路:指定一个脚本包,包含主程序、子程序、配置文件、邮件引擎、输出日志等。
主程序:作为整个脚本的入口,是整个系统的命脉。
配置文件:是一个控制中心,用它来开关各个子程序,指定各个相关联的日志文件。
子程序:这个才是真正的监控脚本,用来监控各个指标。
邮件引擎:是由一个php程序来实现,它可以定义发邮件的服务器、发邮件人以及收邮件人。
输出日志:整个监控系统要有日志输出。
要求:我们的机器角色多种多样,但是所有机器上都要部署同样的监控系统,也就说所有机器不管什么角色,整个程序框架都是一致的,不同的地方在于根据不同的角色,定制不同的配置文件。
程序架构:
主目录 mon
| | | | |
bin conf shares mail log
| | | | |
[main.sh] [ mon.conf] [load.sh 502.sh] [mail.php mail.sh] [ mon.log err.log ]
cd /usr/local/
mkdir mon
cd mon
mkdir bin conf shares mail log
tree ../mon
其中bin下是主程序,conf下是配置文件,shares下是各个监控脚本,mail下是邮件引擎,log下是日志。
下面我发出几个示例脚本
1. main.sh
1. #!/bin/bash
2. #Written by aming.
3.
4. export send=1 #声明一个全局的变量,发邮件的开关,1就发,0不发
5. export addr=`/sbin/ifconfig |grep -A1 'eth0' |grep addr: |awk '{print $2}'|awk -F: '{print $2}'`
6. dir=`pwd`
7. last_dir=`echo $dir|awk -F'/' '{print $NF}'`
8.
9. if [ $last_dir == "bin" ] || [ $last_dir == "bin/" ]; then
10. conf_file="../conf/mon.conf" #配置文件所在的目录,上面的意思是要执行主要程序必须要进入到bin下才可以执行
11. else
12. echo "you shoud cd bin dir"
13. exit
14. fi
15. exec 1>>../log/mon.log 2>>../log/err.log #exec 是用来输出日志的,是记录下面的日志的
16.
17. echo "`date +"%F %T"` load average"
18. /bin/bash ../shares/load.sh #上面输出时间,然后执行他的子脚本
19. #下面是监控负载的,监控502,这里有个开关,上面没有,下面的等于1就执行下面的脚本
20. if grep -q 'to_mon_502=1' $conf_file; then
21. export log=`grep 'logfile=' $conf_file |awk -F '=' '{print $2}' |sed 's/ //g'`
22. /bin/bash ../shares/502.sh
#监控就必须知道访问日志,上面就是根据配置文件来得到访问日志
23. fi
24.
2. mon.conf
1. ## to config the options if to monitor
2.
3. ## cdb
4. to_mon_cdb=0 ##0 or 1, default 0,0 not monitor, 1 monitor
5. cdb_ip=10.20.3.13
6. cdb_port=3315
7. cdb_user=username
8. cdb_pass=passwd
9.
10. ## httpd
11. to_mon_httpd=0
12.
13. ## php
14. to_mon_php_socket=0
15.
16. ## http_code_502
17. to_mon_502=1
18. logfile=/data/log/xxx.xxx.com/access.log
19.
20. ## request_count请求数量
21. to_mon_request_count=0
22. req_log=/data/log/www.discuz.net/access.log
23. domainname=www.discuz.net
24.
25. ## analyse access log avoid wget or curl
26. to_mon_log=0
27.
load是用w和uptime查看 求倒数第三个字段,一分钟之内系统的负载值,有多少进程有多少任务在使用你的cpu
3. load.sh
1. #! /bin/bash
2.
3. ##Writen by aming##
4.
5. load=`uptime |awk -F 'average:' '{print $2}'|cut -d',' -f1|sed 's/ //g' |cut -d. -f1`
6. if [ $load -gt 20 ] && [ $send -eq "1" ]
7. then
8. echo "$addr `date +%T` load is $load" >../log/load.tmp
9. /bin/bash ../mail/mail.sh $addr\_load $load ../log/load.tmp
10. fi
11. echo "`date +%T` load is $load" #如果不大于20,这里就不执行了
12.
/etc/init.d/nginx reload 他网站产生的日志,查看他的状态码,在视频30分钟
4. 502.sh
1.
2. #! /bin/bash
3. d=`date -d "-1 min" +%H:%M` #一分钟检查一次
4. c_502=`grep :$d: $log |grep ' 502 '|wc -l` #检测获得502有几次
5. if [ $c_502 -gt 10 ] && [ $send == 1 ]; then
6. echo "$addr $d 502 count is $c_502">../log/502.tmp #记录临时文件,发给指定的人
7. /bin/bash ../mail/mail.sh $addr\_502 $c_502 ../log/502.tmp
8. fi
9. echo "`date +%T` 502 $c_502"
10.
5. mail.php
<?php
class Smtp
{
/* Public Variables */
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
/* Private Variables */
var $sock;
/* Constractor */
function Smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
{
$this->debug = FALSE;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 30; //is used in fsockopen()
#
$this->auth = $auth;//auth
$this->user = $user;
$this->pass = $pass;
#
$this->host_name = "localhost"; //is used in HELO command
$this->log_file = "";
$this->sock = FALSE;
}
/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
{
$mail_from = $this->get_address($this->strip_comment($from));
$body = ereg_replace("(^|(\r\n))(\.)", "\1.\3", $body);
$header = "MIME-Version:1.0\r\n";
if($mailtype=="HTML"){
$header .= "Content-Type:text/html\r\n";
}
$header .= "To: ".$to."\r\n";
if ($cc != "") {
$header .= "Cc: ".$cc."\r\n";
}
$header .= "From: $from<".$from.">\r\n";
$header .= "Subject: ".$subject."\r\n";
$header .= $additional_headers;
$header .= "Date: ".date("r")."\r\n";
$header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n";
list($msec, $sec) = explode(" ", microtime());
$header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";
$TO = explode(",", $this->strip_comment($to));
if ($cc != "") {
$TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
}
if ($bcc != "") {
$TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
}
$sent = TRUE;
foreach ($TO as $rcpt_to) {
$rcpt_to = $this->get_address($rcpt_to);
if (!$this->smtp_sockopen($rcpt_to)) {
$this->log_write("Error: Cannot send email to ".$rcpt_to."\n");
$sent = FALSE;
continue;
}
if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
$this->log_write("E-mail has been sent to <".$rcpt_to.">\n");
} else {
$this->log_write("Error: Cannot send email to <".$rcpt_to.">\n");
$sent = FALSE;
}
fclose($this->sock);
$this->log_write("Disconnected from remote host\n");
}
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "")
{
if (!$this->smtp_putcmd("HELO", $helo)) {
return $this->smtp_error("sending HELO command");
}
#auth
if($this->auth){
if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
return $this->smtp_error("sending HELO command");
}
if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
return $this->smtp_error("sending HELO command");
}
}
#
if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
return $this->smtp_error("sending MAIL FROM command");
}
if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
return $this->smtp_error("sending RCPT TO command");
}
if (!$this->smtp_putcmd("DATA")) {
return $this->smtp_error("sending DATA command");
}
if (!$this->smtp_message($header, $body)) {
return $this->smtp_error("sending message");
}
if (!$this->smtp_eom()) {
return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
}
if (!$this->smtp_putcmd("QUIT")) {
return $this->smtp_error("sending QUIT command");
}
return TRUE;
}
function smtp_sockopen($address)
{
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx($address);
} else {
return $this->smtp_sockopen_relay();
}
}
function smtp_sockopen_relay()
{
$this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."\n");
$this->log_write("Error: ".$errstr." (".$errno.")\n");
return FALSE;
}
$this->log_write("Connected to relay host ".$this->relay_host."\n");
return TRUE;
}
function smtp_sockopen_mx($address)
{
$domain = ereg_replace("^.+@([^@]+)$", "\1", $address);
if (!@getmxrr($domain, $MXHOSTS)) {
$this->log_write("Error: Cannot resolve MX \"".$domain."\"\n");
return FALSE;
}
foreach ($MXHOSTS as $host) {
$this->log_write("Trying to ".$host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Warning: Cannot connect to mx host ".$host."\n");
$this->log_write("Error: ".$errstr." (".$errno.")\n");
continue;
}
$this->log_write("Connected to mx host ".$host."\n");
return TRUE;
}
$this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n");
return FALSE;
}
function smtp_message($header, $body)
{
fputs($this->sock, $header."\r\n".$body);
$this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> "));
return TRUE;
}
function smtp_eom()
{
fputs($this->sock, "\r\n.\r\n");
$this->smtp_debug(". [EOM]\n");
return $this->smtp_ok();
}
function smtp_ok()
{
$response = str_replace("\r\n", "", fgets($this->sock, 512));
$this->smtp_debug($response."\n");
if (!ereg("^[23]", $response)) {
fputs($this->sock, "QUIT\r\n");
fgets($this->sock, 512);
$this->log_write("Error: Remote host returned \"".$response."\"\n");
return FALSE;
}
return TRUE;
}
function smtp_putcmd($cmd, $arg = "")
{
if ($arg != "") {
if($cmd=="") $cmd = $arg;
else $cmd = $cmd." ".$arg;
}
fputs($this->sock, $cmd."\r\n");
$this->smtp_debug("> ".$cmd."\n");
return $this->smtp_ok();
}
function smtp_error($string)
{
$this->log_write("Error: Error occurred while ".$string.".\n");
return FALSE;
}
function log_write($message)
{
$this->smtp_debug($message);
if ($this->log_file == "") {
return TRUE;
}
$message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
$this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n");
return FALSE;;
}
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);
return TRUE;
}
function strip_comment($address)
{
$comment = "\([^()]*\)";
while (ereg($comment, $address)) {
$address = ereg_replace($comment, "", $address);
}
return $address;
}
function get_address($address)
{
$address = ereg_replace("([ \t\r\n])+", "", $address);
$address = ereg_replace("^.*<(.+)>.*$", "\1", $address);
return $address;
}
function smtp_debug($message)
{
if ($this->debug) {
echo $message;
}
}
}
$file = $argv[2];
$smtpserver = "smtp.qq.com";//SMTP服务器
$smtpserverport = "25";//SMTP服务器端口
$smtpusermail = "1198658@qq.com";//SMTP服务器的用户邮箱,视频40分钟
$smtpemailto = "lishi@139.com";//发送给谁
$smtpuser = "1198658";//SMTP服务器的用户帐号,这个是独立账号
$smtppass = "1212lss";//SMTP服务器的用户密码,独立密码
$mailsubject = $argv[1];//邮件主题
$mailbody = file_get_contents($file);//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
//$smtp->debug = TRUE;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>
要想发邮件的话,首先要有php支持,若你没有安装过lamp或者lnmp,则需要运行yum install -y php-cli 安装。
然后运行 php mail.php "邮箱主题写在这里" "/tmp/test.txt" 。其中,/tmp/test.txt 内容为邮件内容。
php -v 看他的版本
如果有报错,就是他没有定义时间
Asia/Chongqing
在配置文件 vim /etc/php.ini
搜索 /timezone 找到把他打开就可以了date.time = 'Asia/Chongqing'
发告警邮件的shell脚本,利用mail.php 发邮件
6. mail.sh
1. #! /bin/bash
2. log=$1
3. t_s=`date +%s`
4. t_s2=`date -d "2 hours ago" +%s` #这里是为了求两次告警的时间差值
5. if [ ! -f /tmp/$log ]
6. then
7. echo $t_s2 > /tmp/$log #差值通过这里获得
8. fi
9. t_s2=`tail -1 /tmp/$log|awk '{print $1}'`
10. echo $t_s>>/tmp/$log
11. v=$[$t_s-$t_s2]
12. #echo $v
13. if [ $v -gt 3600 ]
14. then
15. /usr/bin/php ../mail/mail.php "$1 $2" "$3" #$1 $2是发邮件的主题,$3是发邮件的文件
16. echo "0" > /tmp/$log.txt #上面发完告警后,给他清空
17. else
18. if [ ! -f /tmp/$log.txt ]
19. then
20. echo "0" > /tmp/$log.txt
21. fi
22. nu=`cat /tmp/$log.txt`
23. nu2=$[$nu+1]
24. echo $nu2>/tmp/$log.txt
25. if [ $nu2 -gt 10 ]
26. then
27. /dir/to/php ../mail/mail.php "trouble continue 10 min $1 $2 " "$3"
28. echo "0" > /tmp/$log.txt
29. fi
30. fi
31.
第五部分shell项目一监控脚本的更多相关文章
- 【不积跬步,无以致千里】五个常用的Linux监控脚本代码
为大家提供五个常用Linux监控脚本(查看主机网卡流量.系统状况监控.监控主机的磁盘空间,当使用空间超过90%就通过发mail来发警告.监控CPU和内存的使用情况.全方位监控主机),有需要的朋友不妨看 ...
- 五个常用的Linux监控脚本代码
bash中 2>&1 & 的解释 1.首先,bash中0,1,2三个数字分别代表STDIN_FILENO.STDOUT_FILENO.STDERR_FILENO,即标准输入(一般 ...
- centos shell编程6一些工作中实践脚本 nagios监控脚本 自定义zabbix脚本 mysql备份脚本 zabbix错误日志 直接送给bc做计算 gzip innobackupex/Xtrabackup 第四十节课
centos shell编程6一些工作中实践脚本 nagios监控脚本 自定义zabbix脚本 mysql备份脚本 zabbix错误日志 直接送给bc做计算 gzip innobacku ...
- Linux 服务器系统监控脚本 Shell【转】
转自: Linux 服务器系统监控脚本 Shell - 今日头条(www.toutiao.com)http://www.toutiao.com/i6373134402163048961/ 本程序在Ce ...
- Linux centosVMware运行告警系统、分发系统-expect讲解、自动远程登录后,执行命令并退出、expect脚本传递参数、expect脚本同步文件、指定host和要同步的文件、shell项目-分发系统-构建文件分发系统、分发系统-命令批量执行
一运行告警系统 创建一个任务计划crontab -e 每一分钟都执行一次 调试时把主脚本里边log先注释掉 再次执行 没有发现502文件说明执行成功了,每日有错误,本机IP 负载不高 二.分发系统-e ...
- shell监控脚本实例—监控mysql主从复制
分享一例shell脚本,用于监测mysql数据库的主从复制,有需要的朋友不妨参考学习下. 转自:http://www.jbxue.com/article/14103.html(转载请注明出处) 本节内 ...
- shell监控脚本
序言: 前几天一好友问我服务器监控怎么做?你们公司的监控是怎么做的?有什么开源的监控软件推荐?常见的开源的监控软件当然首先推荐ZABBIX,分布式够强大,而且很多公司都在用,我问他具体什么需求,能监控 ...
- linux100day(day8)--shell监控脚本练习
这是一个大型的监控脚本,方便于查看硬盘,网络,负载,内核版本等系统信息. 本脚本来自于github的atarallo,我对脚本做出了改编和一些注释,尽量让新手也能理解,这个脚本逻辑清楚简单,适合用于练 ...
- zabbix客户端监控脚本shell
zabbix客户端监控脚本shell #!/bin/sh sleep 3 zabbixdir=`pwd` zabbix_version=4.2.5 ###指定版本,最好和server端吻合版本,可以自 ...
随机推荐
- 如何制作 Ubuntu 系统的 USB 启动盘
下载 Ubuntu 打开 http://mirrors.ustc.edu.cn 获取安装镜像 --> 获取 ISO 刻录 Ubuntu 到 U 盘 打开 http://rufus.akeo.ie ...
- ORB-SLAM (四)Initializer单目初始化
一. 通过对极约束并行计算F和H矩阵初始化 VO初始化目的是为了获得准确的帧间相对位姿,并通过三角化恢复出初始地图点.初始化方法要求适用于不同的场景(特别是平面场景),并且不要进行人为的干涉,例如选取 ...
- python中- \r用法
# \r 默认表示将输出的内容返回到第一个指针,这样的话,后面的内容会覆盖前面的内容 def main(): for i in range(65,91): s="\r{name:s}&quo ...
- bash特性-命令历史命令行编辑
bash: GUI:Gnome,KDE,XFCE CLI:sh,csh,bash,ksh,tcsh,zsh shell,子shell tree:查看目录树 pstree:查看进程目录树 bash: 1 ...
- Unity Lighting - Choosing a Lighting Technique 选择照明技术(一)
Choosing a Lighting Technique 选择照明技术 https://unity3d.com/cn/learn/tutorials/topics/graphics/choosi ...
- Unity编辑器 - TreeView控件笔记
用起来有一些规则,写个简单的案例以备查阅: using System.Collections.Generic; using UnityEditor.IMGUI.Controls; using Unit ...
- Memcache的客户端连接系列(四) PHP
关键词: Memcached PHP 客户端 声明:本文并非原创,转自华为云帮助中心的分布式缓存服务(Memcached)的用户指南.客户端连接方法通用,故摘抄过来分享给大家. PHP客户端 Re ...
- Docker容器的搭建
Docker容器的搭建 一.先从Docker Hub上面拉取一个基础镜像 命令:docker pull ubuntu 命令说明:pull:拉取镜像的命令,ubuntu:拉取镜像的名称 扩展命令: 命令 ...
- 3.azkaban3.0测试
测试目标 azkaban多executor下flow的分配方式 azkaban可以同时执行的flow\job个数 azkaban单个job最小使用的内存 相关配置 executor最大线程数: exe ...
- HDU 1007 Quoit Design(计算几何の最近点对)
Problem Description Have you ever played quoit in a playground? Quoit is a game in which flat rings ...