CentOS Shell Programming 3 "alarm system" 37th session
The first half of the class
The second half of the class
The entire project does not have any architecture, is single-machine, without the concept of server-side and client
Just a simple call to shell script, child shell, by adding more shell script extension features
Mail.sh: Do Mail convergence
Uptime or W get load average
Need to install PHP environment
Yum install-y php
Requirements: Use the shell to customize a variety of personalized alarm tools, but the need for unified management, standardized management.
Idea: Specify a script package that contains the main program, subroutine, configuration file, mail engine, output log, and so on.
Main program: As the entire script portal, is the lifeblood of the entire system.
Configuration file: is a control center that uses it to switch individual subroutines, specifying each associated log file.
Subroutine: This is the real monitoring script, used to monitor each indicator.
Mail Engine: It is implemented by a PHP program, it can define the server to send the mail, the sender and the mail recipient.
Output log: The entire monitoring system should have a log output.
Requirements: Our machine roles are varied, but the same monitoring system is deployed on all machines, and the entire program framework is consistent, regardless of the role of all machines, depending on the role of the different configuration files.
Program Architecture:
(Main directory Mon)
____________________|_______________________________
| | | | |
Bin Conf shares mail log
| | | | |
[main.sh] [mon.conf] [load.sh 502.sh] [mail.php mail.sh] [Mon.log Err.log]
Under Bin is the main program
Conf is the configuration file
Shares is the various monitoring scripts
Mail engine under Mail
Log is the journal.
Here I send out a few sample scripts
1. main.sh
#!/bin/bash
#Written by Aming.
# whether to send mail switch
Export send=1
# Filter IP Address
Export addr= '/sbin/ifconfig |grep-a1 ' eth0 ' |grep addr: |awk ' {print $} ' |awk-f: ' {print $} '
Dir= ' pwd '
# requires only the last level of directory name
Last_dir= ' echo $dir |awk-f '/' {print $NF} ' #打印最后一段print $NF
# The purpose of this is to ensure that we are in the bin directory when the script is executed, otherwise the monitoring scripts, mails, and logs may not be found
if [$last _dir = = "Bin"] | | [$last _dir = = "bin/"]; Then
Conf_file= ". /conf/mon.conf "
Else
echo "You shoud cd bin dir"
Exit
Fi
exec 1>>. /log/mon.log 2>> /log/err.log #所有子脚本的错误都重定向到/log/err.log
echo "' Date +"%F%T "' Load average '
/bin/bash. /shares/load.sh #调用子脚本
#先检查配置文件中是否需要监控502
If Grep-q ' to_mon_502=1 ' $conf _file; Then
Export log= ' grep ' logfile= ' $conf _file |awk-f ' = ' {print $} ' |sed ' s///g '
/bin/bash. /shares/502.sh
Fi
2. configuration file mon.conf
# to config-the options if to monitor
# # CDB primarily defines MySQL server address, port, and user, password
To_mon_cdb=0 # #0 or 1, default 0,0 not monitor, 1 monitor
cdb_ip=10.20.3.13
cdb_port=3315
Cdb_user=username
cdb_pass=passwd
# # HTTPD If 1 is monitored, 0 not monitored
To_mon_httpd=0
# # PHP If it is 1 monitor, 0 not monitor
To_mon_php_socket=0
# # http_code_502 need to define the path to the access log
To_mon_502=1
Logfile=/data/log/xxx.xxx.com/access.log
# # Request_count defines the log path and domain name
To_mon_request_count=0
Req_log=/data/log/www.discuz.net/access.log
Domainname=www.discuz.net
3. load.sh
#! /bin/bash
# #Writen by aming##
load= ' uptime |awk-f ' average: ' {print $} ' |cut-d ', '-f1|sed ' s///g ' |cut-d.-f1 ' #将空格去掉 1 minutes 5 minutes 15 minutes
If [$load-gt] && [$send-eq "1"]
Then
echo "$addr ' date +%t ' load is $load" ... /log/load.tmp
/bin/bash. /mail/mail.sh $addr \_load $load. /log/load.tmp
Fi
echo "' Date +%t ' load is $load"
4.502.sh
#! /bin/bash
D= ' date-d '-1 min "+%h:%m"
C_502= ' grep: $d: $log |grep ' 502 ' |wc-l '
If [$c _502-gt] && [$send = = 1]; Then
echo "$addr $d 502 count is $c _502" ... /log/502.tmp
/bin/bash. /mail/mail.sh $addr \_502 $c _502. /log/502.tmp
Fi
echo "' Date +%t ' 502 $c _502"
disk.sh
#! /bin/bash
# #Writen by aming##
Rm-f. /log/disk.tmp
For R in ' Df-h |awk-f ' [%]+ ' {print $} ' |grep-v use '
Do
If [$r-gt] && [$send-eq "1"]
Then
echo "$addr ' date +%t ' disk useage is $r" >> /log/disk.tmp
Fi
If [-F. /LOG/DISK.TMP]
Then
Df-h >>. /log/disk.tmp
/bin/bash. /mail/mail.sh $addr \_disk $r. /log/disk.tmp
echo "' Date +%t ' disk useage is Nook"
Else
echo "' Date +%t ' disk useage is OK"
Fi
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 = +, $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 ("(^| ( \ \ \)] (\) "," \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 ("^[email protected" ([^@]+) $ "," \1 ", $address);
if ([email protected] ($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 ([email protected]_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 server
$smtpserverport = "";//smtp server port
$smtpusermail = "[email protected]";//smtp server's user mailbox
$smtpemailto = "[email protected]";//Send To whom
$smtpuser = "1198658"; user account for//SMTP server
$smtppass = "1212LSS"; user password for//SMTP server
$mailsubject = $ARGV [1];//message subject
$mailbody = file_get_contents ($file);//mail content
$mailtype = "HTML";//Message Format (html/txt), TXT as text mail
$SMTP = new SMTP ($smtpserver, $smtpserverport, True, $smtpuser, $smtppass);//A true in this indicates that authentication is used, otherwise no authentication is used.
$SMTP->debug = true;//whether to display debug information sent
$smtp->sendmail ($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>
If you want to send an e-mail, you must first have PHP support, if you have not installed lamp or LNMP, you need to run the Yum install-y PHP installation.
Then run PHP mail.php "email subject written here" "/tmp/test.txt". Where/tmp/test.txt content is the content of the message.
6. mail.sh
#!/bin/bash
Log=$1
t_s= ' date + '%s '
T_s2= ' date-d " -2hour" + "%s" '
if [!-f/tmp/$log]
Then
echo $t _s2 >/tmp/$log
Fi
T_s2= ' tail-1/tmp/$log |awk ' {print '} '
echo $t _s>>/tmp/$log
v=$[$t _s-$t _s2]
Echo $v
If [$v-GT 3600]
Then
/dir/to/php. /mail/mail.php "$ $" "$"
echo "0" >/tmp/$log. txt
Else
if [!-f/tmp/$log. txt]
Then
echo "0" >/tmp/$log. txt
Fi
Nu= ' cat/tmp/$log. txt '
nu2=$[$nu +1]
echo $nu 2>/tmp/$log. txt
If [$nu 2-GT 10]
Then
/dir/to/php. /mail/mail.php "Trouble continue ten min $"
echo "0" >/tmp/$log. txt
Fi
Fi
Monitoring Disk disk.sh
The following two partitions do not require monitoring
Tmfs/dev/shm
/boot
awk Cutting Df-h
For R in ' Df-h |awk-f ' [%]+ ' {print $} ' |grep-v use '
Delimiter: One or more spaces or one or more percent signs as separators, then take out the 5th paragraph
Monitor MySQL master and slave
status=$ (/usr/bin/mysql-uroot-p11111-s/var/lib/mysql/mysql.sock-e "show slave status\g" | grep-i "Running")
Monitoring memory
grep free-m
Monitoring IO
Vmstat 1
F
CentOS Shell Programming 3 "alarm system" 37th session