PHP+shell脚本操作Memcached和Apache Status的实例分享


Posted in PHP onMarch 11, 2016

memcached 进程启动及监控
1.memcached_inc.sh
设置路径,端口等讯息。

#!/bin/sh 
 
#config include 
 
HOST=$(hostname) 
SITE="mysite" 
PORT=11211 
 
MEMCACHED_PID_FILE="/tmp/memcached.pid" 
MEMCACHED_DAEMON_PID_FILE="/tmp/memcached_daemon.pid" 
 
MEMCACHED="memcached -d -m 64 -p $PORT -u memcache -l 127.0.0.1 -P $MEMCACHED_PID_FILE" 
MEMCACHED_DAEMON_FILE="memcached_daemon.sh" 
 
ERROR_LOG_FILE="${ROOT}/memcached_${SITE}_${HOST}_${PORT}.log"

2.gm_memcached.sh
控制memcached 启动,停止,重启。

#!/bin/sh 
 
#memcached start and stop 
#$1 action 
 
ROOT=$(cd "$(dirname "$0")"; pwd) 
 
. ${ROOT}/memcached_inc.sh 
 
 
start() { 
 
 if [ -f "$MEMCACHED_PID_FILE" ] && [ -s "$MEMCACHED_PID_FILE" ]; then 
  printf "memcached already running\n" 
 else 
  printf "starting memcached\n" 
  $MEMCACHED 
 
  sleep 2 
 
  PID=$(cat $MEMCACHED_PID_FILE) 
  printf "memcached is started PID:$PID\n" 
 
  printf "starting memcached daemon\n" 
  ${ROOT}/${MEMCACHED_DAEMON_FILE} & 
  DAEMON_PID=$! 
  echo ${DAEMON_PID} > ${MEMCACHED_DAEMON_PID_FILE} 
  printf "memcached daemon is started PID:${DAEMON_PID}\n" 
 fi 
 
} 
 
 
stop() { 
 
 if [ -f "$MEMCACHED_DAEMON_PID_FILE" ] && [ -s "$MEMCACHED_DAEMON_PID_FILE" ]; then 
  DAEMON_PID=$(cat $MEMCACHED_DAEMON_PID_FILE) 
  rm -f ${MEMCACHED_DAEMON_PID_FILE} 
  if [ ! -z ${DAEMON_PID} ]; then 
   kill -9 ${DAEMON_PID} 
  fi 
  printf "memcached daemon is stopped\n" 
 else 
  printf "no memcached daemon running\n" 
 fi 
 
 sleep 1 
 
 if [ -f "$MEMCACHED_PID_FILE" ] && [ -s "$MEMCACHED_PID_FILE" ]; then 
  PID=$(cat $MEMCACHED_PID_FILE) 
  rm -f ${MEMCACHED_PID_FILE} 
  if [ ! -z ${PID} ]; then 
   kill -9 ${PID} 
  fi 
  printf "memcached is stopped\n" 
 else 
  printf "no memcached running\n" 
 fi 
 
} 
 
 
case "$1" in 
 
 start) 
  start 
  ;; 
 
 stop) 
  stop 
  ;; 
 
 restart) 
  stop 
  sleep 3 
  start 
  ;; 
 
 *) 
  printf "Usage:$0 {start|stop|restart}\n" 
  exit 1 
 
esac 
 
exit 0

3.memcached_daemon.sh
监控memcached 进程,如进程失效则自动启动。

#!/bin/sh 
 
#memcached daemon 
 
ROOT=$(cd "$(dirname "$0")"; pwd) 
 
. ${ROOT}/memcached_inc.sh 
 
 
while : 
do 
 if [ -f "$MEMCACHED_PID_FILE" ] && [ -s "$MEMCACHED_PID_FILE" ]; then 
  PID=$(cat $MEMCACHED_PID_FILE) 
 else 
  PID="" 
 fi 
  
 if [ -z "$PID" ] || [ -z $(ps aux|awk '{print $2}' | grep "^$PID$") ]; then 
  $MEMCACHED 
  sleep 1 
  printf "[$(date +%Y-%m-%d' '%H:%M:%S)] ${SITE} ${HOST} memcached ${PORT} is restarted\n" >> $ERROR_LOG_FILE 
  echo "Subject: ${SITE} ${HOST} memcached ${PORT} is restarted $(date +%Y-%m-%d' '%H:%M:%S)" | sendmail me@gmail.com 
 fi 
 
 sleep 5 
 
done 
 
exit 0

使用方法:

./gm_memcached.sh start #启动memcached 
./gm_memcached.sh stop #停止memcached 
./gm_memcached.sh restart #重启memcached

shell 记录apache status并自动更新到数据库
1. 获取apache status
monitor_log.sh

#!/bin/bash 
 
#连接数 
site_connects=$(netstat -ant | grep $ip:80 | wc -l) 
#当前连接数 
site_cur_connects=$(netstat -ant | grep $ip:80 | grep EST | wc -l) 
 
#apache 
apache_speed=$(netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}') 
 
printf "[#start#]\n$(date '+%Y-%m-%d %H:%M:%S')\n" 
printf "connects:${site_connects}\n" 
printf "cur connects:${site_cur_connects}\n" 
printf "apache_speed:\n${apache_speed}\n[#end#]\n\n" 
 
exit 0

在终端设置crontab执行

* * * * * /home/fdipzone/monitor_log.sh >> /home/fdipzone/monitor.log

2. 将apache status log 写入数据库
save_monitor_log.php

<?php 
 
$logfile = dirname(__FILE__).'/monitor.log'; 
 
$dbconfig = array( 
   'host' => '192.168.1.100', 
   'username' => 'username', 
   'password' => 'password', 
   'dbname' => 'mydb', 
   'tabname' => 'monitor_log' 
); 
 
$obj = new SaveMonitorLog($dbconfig, 'myweb'); 
$obj->load($logfile); 
 
 
// ?取monitor log,??入db,查看db 
class SaveMonitorLog{ // class start 
 
 private $_apache_state = array('TIME_WAIT', 'CLOSE_WAIT', 'SYN_SENT', 'SYN_RECV', 'FIN_WAIT1', 'FIN_WAIT2', 'ESTABLISHED', 'LAST_ACK', 'CLOSING'); 
 private $_dbconfig = array(); 
 private $_site = null; 
 
 
 /** init */ 
 public function __construct($dbconfig=array(), $site='web'){ 
  if(!isset($dbconfig['host']) || !isset($dbconfig['username']) || !isset($dbconfig['password']) || !isset($dbconfig['dbname']) || !isset($dbconfig['tabname'])){ 
   $this->debug('dbconfig error'); 
  } 
  $this->_dbconfig = $dbconfig; 
  $this->_site = $site; 
  $this->connectdb(); 
 } 
 
 
 /** load data 
 * @param String $logfile log文件 
 * @return boolean 
 */ 
 public function load($logfile){ 
 
  // ?取log?? 
  if(file_exists($logfile)){ 
   $logdata = file_get_contents($logfile); 
   // 清空monitor.log 
   file_put_contents($logfile, '', true); 
  }else{ 
   return false; 
  } 
 
  // 正?t分析?? [#start#]*[#end#] 
  preg_match_all('/
#start#
(.*?)
#end#
.*?/si', $logdata, $data); 
 
  if(isset($data[1]) && count($data[1])>0){ 
   $alldata = $data[1]; 
   foreach($alldata as $val){ 
    $indb = $this->parser($val); 
    $newid = $this->addtodb($indb); 
   } 
  } 
 
 } 
 
 
 /** parser data 
 * @param Array $data 
 * @return Array 
 */ 
 private function parser($data){ 
  $indb = array(); 
  $tmp = explode(chr(10), $data); // 按?Q行分隔 
 
  $indb['site'] = $this->_site; 
  $indb['addtime'] = $tmp[1]; 
  $indb['connects'] = array_pop(explode(':',$tmp[2])); 
  $indb['cur_connects'] = array_pop(explode(':',$tmp[3])); 
 
  for($i=5, $max=count($tmp)-2; $i<$max; $i++){ 
   list($key, $num) = explode(' ', $tmp[$i]); 
   if(in_array($key, $this->_apache_state)){ 
    $indb[$key] = $num; 
   } 
  } 
 
  return $indb; 
 } 
 
 
 /** connect db */ 
 private function connectdb(){ 
  $conn=@mysql_connect($this->_dbconfig['host'], $this->_dbconfig['username'], $this->_dbconfig['password']) or die(mysql_error()); 
  mysql_select_db($this->_dbconfig['dbname'], $conn) or die(mysql_error()); 
 } 
 
 
 /** add to db */ 
 private function addtodb($indb){ 
  $insertkey = ''; 
  $insertval = ''; 
  if($indb){ 
   foreach($indb as $key=>$val){ 
    $insertkey .= $insertkey? " ,".$key : $key; 
    $insertval .= $insertval? " ,'".mysql_escape_string(trim($val))."'" : "'".mysql_escape_string(trim($val))."'"; 
   } 
   $sqlstr = "insert into ".$this->_dbconfig['tabname']."($insertkey) values($insertval)"; 
   $query = @mysql_query($sqlstr) or die(mysql_error()); 
   $id = mysql_insert_id(); 
   return $id? $id : false; 
  } 
 } 
 
 
 /** debug */ 
 private function debug($msg){ 
  exit($msg."\r\n"); 
 } 
 
 
} // class end 
 
?>

在终端crontab执行

0 0 * * * php /home/fdipzone/save_monitor_log.php

 
table monitor_log struct

CREATE TABLE IF NOT EXISTS `monitor_log` ( 
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
 `site` varchar(20) NOT NULL, 
 `connects` int(10) unsigned NOT NULL DEFAULT '0', 
 `cur_connects` int(10) unsigned NOT NULL DEFAULT '0', 
 `TIME_WAIT` int(10) unsigned NOT NULL DEFAULT '0', 
 `CLOSE_WAIT` int(10) unsigned NOT NULL DEFAULT '0', 
 `SYN_SENT` int(10) unsigned NOT NULL DEFAULT '0', 
 `SYN_RECV` int(10) unsigned NOT NULL DEFAULT '0', 
 `FIN_WAIT1` int(10) unsigned NOT NULL DEFAULT '0', 
 `FIN_WAIT2` int(10) unsigned NOT NULL DEFAULT '0', 
 `ESTABLISHED` int(10) unsigned NOT NULL DEFAULT '0', 
 `LAST_ACK` int(10) unsigned NOT NULL DEFAULT '0', 
 `CLOSING` int(10) unsigned NOT NULL DEFAULT '0', 
 `addtime` datetime NOT NULL, 
 PRIMARY KEY (`id`), 
 KEY `connects` (`connects`), 
 KEY `cur_connects` (`cur_connects`), 
 KEY `TIME_WAIT` (`TIME_WAIT`), 
 KEY `CLOSE_WAIT` (`CLOSE_WAIT`), 
 KEY `SYN_SENT` (`SYN_SENT`), 
 KEY `SYN_RECV` (`SYN_RECV`), 
 KEY `FIN_WAIT1` (`FIN_WAIT1`), 
 KEY `FIN_WAIT2` (`FIN_WAIT2`), 
 KEY `ESTABLISHED` (`ESTABLISHED`), 
 KEY `LAST_ACK` (`LAST_ACK`), 
 KEY `CLOSING` (`CLOSING`), 
 KEY `addtime` (`addtime`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
PHP 相关文章推荐
聊天室php&amp;mysql(二)
Oct 09 PHP
php面向对象全攻略 (十七) 自动加载类
Sep 30 PHP
PHP新手入门学习方法
May 08 PHP
PHP读取网页文件内容的实现代码(fopen,curl等)
Jun 23 PHP
浅析is_writable的php实现
Jun 18 PHP
php把数据表导出为Excel表的最简单、最快的方法(不用插件)
May 10 PHP
PHP输出英文时间日期的安全方法(RFC 1123格式)
Jun 13 PHP
php正则匹配html中带class的div并选取其中内容的方法
Jan 13 PHP
PHP中使用file_get_contents post数据代码例子
Feb 13 PHP
php array_slice 取出数组中的一段序列实例
Nov 04 PHP
Thinkphp5.0框架视图view的模板布局用法分析
Oct 12 PHP
PHP程序员简单的开展服务治理架构操作详解(一)
May 14 PHP
PHP批量去除BOM头内容信息代码
Mar 11 #PHP
PHP中调用C/C++制作的动态链接库的教程
Mar 10 #PHP
php实现无限级分类查询(递归、非递归)
Mar 10 #PHP
Zend Framework教程之Application和Bootstrap用法详解
Mar 10 #PHP
Zend Framework教程之配置文件application.ini解析
Mar 10 #PHP
PHP浮点数的一个常见问题
Mar 10 #PHP
简单谈谈php浮点数精确运算
Mar 10 #PHP
You might like
php使用Smarty的相关注意事项及访问变量的几种方式
2011/12/08 PHP
PHP编程快速实现数组去重的方法详解
2017/07/22 PHP
jquery 注意事项与常用语法小结
2010/06/07 Javascript
js arguments对象应用介绍
2012/11/28 Javascript
javascript生成随机颜色示例代码
2014/05/05 Javascript
让浏览器DOM元素最后加载的js方法
2014/07/29 Javascript
js不能获取隐藏的div的宽度只能先显示后获取
2014/09/04 Javascript
js实现当鼠标移到表格上时显示这一格全部内容的代码
2016/06/12 Javascript
AngularJS基础 ng-mousemove 指令简单示例
2016/08/02 Javascript
JS实现滑动门效果的方法详解
2016/12/19 Javascript
简单实现js悬浮导航效果
2017/02/05 Javascript
JS去掉字符串前后空格、阻止表单提交的实现代码
2017/06/08 Javascript
基于Vue生产环境部署详解
2017/09/15 Javascript
JS装饰器函数用法总结
2018/04/21 Javascript
vue兄弟组件传递数据的实例
2018/09/06 Javascript
在Vue 中使用Typescript的示例代码
2018/09/10 Javascript
vue、react等单页面项目部署到服务器的方法及vue和react的区别
2018/09/29 Javascript
vue如何根据网站路由判断页面主题色详解
2018/11/02 Javascript
图文讲解用vue-cli脚手架创建vue项目步骤
2019/02/12 Javascript
Vue3.x源码调试的实现方法
2019/10/13 Javascript
原生js实现分页效果
2020/09/23 Javascript
ES6学习教程之Promise用法详解
2020/11/22 Javascript
python实现的希尔排序算法实例
2015/07/01 Python
Python中import导入上一级目录模块及循环import问题的解决
2016/06/04 Python
浅谈使用Python变量时要避免的3个错误
2017/10/30 Python
python3读取csv和xlsx文件的实例
2018/06/22 Python
python代码实现将列表中重复元素之间的内容全部滤除
2020/05/22 Python
keras分类之二分类实例(Cat and dog)
2020/07/09 Python
iframe与window.onload如何使用详解
2020/05/07 HTML / CSS
什么是三层交换,说说和路由的区别在那里
2014/09/01 面试题
成龙霸王洗发水广告词
2014/03/14 职场文书
2014年中职班主任工作总结
2014/12/16 职场文书
公司借条范本
2015/05/25 职场文书
2016年元旦主持词
2015/07/06 职场文书
2019个人工作总结
2019/06/21 职场文书
python opencv旋转图片的使用方法
2021/06/04 Python