search
HomeBackend DevelopmentPHP TutorialExample sharing of PHP shell script operating Memcached and Apache Status, memcachedapache_PHP tutorial

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

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

<&#63;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; 
  } 
 
  // 正則分析數據 [#start#]*[#end#] 
  preg_match_all('/
#start#
(.*&#63;)
#end#
.*&#63;/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); // 按換行分隔 
 
  $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&#63; " ,".$key : $key; 
    $insertval .= $insertval&#63; " ,'".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&#63; $id : false; 
  } 
 } 
 
 
 /** debug */ 
 private function debug($msg){ 
  exit($msg."\r\n"); 
 } 
 
 
} // class end 
 
&#63;> 

在终端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+shell实现多线程的方法
  • php-fpm开机自动启动Shell脚本
  • Shell、Perl、Python、PHP访问 MySQL 数据库代码实例
  • Shell脚本中实现更新PHP5
  • Shell脚本实现启动PHP内置FastCGI Server
  • PHP和Shell实现检查SAMBA与NFS Server是否存在
  • Ruby、PHP、Shell实现求50以内的素数
  • shell脚本联合PHP脚本采集网站的pv和alexa排名
  • php管理nginx虚拟主机shell脚本实例
  • 监控服务器swap并重启php的Shell脚本

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1108606.htmlTechArticlePHP+shell脚本操作Memcached和Apache Status的实例分享,memcachedapache memcached 进程启动及监控 1.memcached_inc.sh 设置路径,端口等讯息。 #!/bin/sh #conf...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!