PHP+shell脚本操作Memcached和Apache Status的实例分享
memcached进程启动及监控
1.memcached_inc.sh
设置路径,端口等讯息。
#!/bin/sh
#configinclude
HOST=$(hostname)
SITE="mysite"
PORT=11211
MEMCACHED_PID_FILE="/tmp/memcached.pid"
MEMCACHED_DAEMON_PID_FILE="/tmp/memcached_daemon.pid"
MEMCACHED="memcached-d-m64-p$PORT-umemcache-l127.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
#memcachedstartandstop
#$1action
ROOT=$(cd"$(dirname"$0")";pwd)
.${ROOT}/memcached_inc.sh
start(){
if[-f"$MEMCACHED_PID_FILE"]&&[-s"$MEMCACHED_PID_FILE"];then
printf"memcachedalreadyrunning\n"
else
printf"startingmemcached\n"
$MEMCACHED
sleep2
PID=$(cat$MEMCACHED_PID_FILE)
printf"memcachedisstartedPID:$PID\n"
printf"startingmemcacheddaemon\n"
${ROOT}/${MEMCACHED_DAEMON_FILE}&
DAEMON_PID=$!
echo${DAEMON_PID}>${MEMCACHED_DAEMON_PID_FILE}
printf"memcacheddaemonisstartedPID:${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"memcacheddaemonisstopped\n"
else
printf"nomemcacheddaemonrunning\n"
fi
sleep1
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"memcachedisstopped\n"
else
printf"nomemcachedrunning\n"
fi
}
case"$1"in
start)
start
;;
stop)
stop
;;
restart)
stop
sleep3
start
;;
*)
printf"Usage:$0{start|stop|restart}\n"
exit1
esac
exit0
3.memcached_daemon.sh
监控memcached进程,如进程失效则自动启动。
#!/bin/sh
#memcacheddaemon
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$(psaux|awk'{print$2}'|grep"^$PID$")];then
$MEMCACHED
sleep1
printf"[$(date+%Y-%m-%d''%H:%M:%S)]${SITE}${HOST}memcached${PORT}isrestarted\n">>$ERROR_LOG_FILE
echo"Subject:${SITE}${HOST}memcached${PORT}isrestarted$(date+%Y-%m-%d''%H:%M:%S)"|sendmailme@gmail.com
fi
sleep5
done
exit0
使用方法:
./gm_memcached.shstart#启动memcached ./gm_memcached.shstop#停止memcached ./gm_memcached.shrestart#重启memcached
shell记录apachestatus并自动更新到数据库
1.获取apachestatus
monitor_log.sh
#!/bin/bash
#连接数
site_connects=$(netstat-ant|grep$ip:80|wc-l)
#当前连接数
site_cur_connects=$(netstat-ant|grep$ip:80|grepEST|wc-l)
#apache
apache_speed=$(netstat-n|awk'/^tcp/{++S[$NF]}END{for(ainS)printa,S[a]}')
printf"[#start#]\n$(date'+%Y-%m-%d%H:%M:%S')\n"
printf"connects:${site_connects}\n"
printf"curconnects:${site_cur_connects}\n"
printf"apache_speed:\n${apache_speed}\n[#end#]\n\n"
exit0
在终端设置crontab执行
*****/home/fdipzone/monitor_log.sh>>/home/fdipzone/monitor.log
2.将apachestatuslog写入数据库
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=newSaveMonitorLog($dbconfig,'myweb');
$obj->load($logfile);
//讀取monitorlog,記錄入db,查看db
classSaveMonitorLog{//classstart
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*/
publicfunction__construct($dbconfig=array(),$site='web'){
if(!isset($dbconfig['host'])||!isset($dbconfig['username'])||!isset($dbconfig['password'])||!isset($dbconfig['dbname'])||!isset($dbconfig['tabname'])){
$this->debug('dbconfigerror');
}
$this->_dbconfig=$dbconfig;
$this->_site=$site;
$this->connectdb();
}
/**loaddata
*@paramString$logfilelog文件
*@returnboolean
*/
publicfunctionload($logfile){
//讀取log數據
if(file_exists($logfile)){
$logdata=file_get_contents($logfile);
//清空monitor.log
file_put_contents($logfile,'',true);
}else{
returnfalse;
}
//正則分析數據[#start#]*[#end#]
preg_match_all('/
#start#
(.*?)
#end#
.*?/si',$logdata,$data);
if(isset($data[1])&&count($data[1])>0){
$alldata=$data[1];
foreach($alldataas$val){
$indb=$this->parser($val);
$newid=$this->addtodb($indb);
}
}
}
/**parserdata
*@paramArray$data
*@returnArray
*/
privatefunctionparser($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;
}
/**connectdb*/
privatefunctionconnectdb(){
$conn=@mysql_connect($this->_dbconfig['host'],$this->_dbconfig['username'],$this->_dbconfig['password'])ordie(mysql_error());
mysql_select_db($this->_dbconfig['dbname'],$conn)ordie(mysql_error());
}
/**addtodb*/
privatefunctionaddtodb($indb){
$insertkey='';
$insertval='';
if($indb){
foreach($indbas$key=>$val){
$insertkey.=$insertkey?",".$key:$key;
$insertval.=$insertval?",'".mysql_escape_string(trim($val))."'":"'".mysql_escape_string(trim($val))."'";
}
$sqlstr="insertinto".$this->_dbconfig['tabname']."($insertkey)values($insertval)";
$query=@mysql_query($sqlstr)ordie(mysql_error());
$id=mysql_insert_id();
return$id?$id:false;
}
}
/**debug*/
privatefunctiondebug($msg){
exit($msg."\r\n");
}
}//classend
?>
在终端crontab执行
00***php/home/fdipzone/save_monitor_log.php
tablemonitor_logstruct
CREATETABLEIFNOTEXISTS`monitor_log`( `id`int(10)unsignedNOTNULLAUTO_INCREMENT, `site`varchar(20)NOTNULL, `connects`int(10)unsignedNOTNULLDEFAULT'0', `cur_connects`int(10)unsignedNOTNULLDEFAULT'0', `TIME_WAIT`int(10)unsignedNOTNULLDEFAULT'0', `CLOSE_WAIT`int(10)unsignedNOTNULLDEFAULT'0', `SYN_SENT`int(10)unsignedNOTNULLDEFAULT'0', `SYN_RECV`int(10)unsignedNOTNULLDEFAULT'0', `FIN_WAIT1`int(10)unsignedNOTNULLDEFAULT'0', `FIN_WAIT2`int(10)unsignedNOTNULLDEFAULT'0', `ESTABLISHED`int(10)unsignedNOTNULLDEFAULT'0', `LAST_ACK`int(10)unsignedNOTNULLDEFAULT'0', `CLOSING`int(10)unsignedNOTNULLDEFAULT'0', `addtime`datetimeNOTNULL, PRIMARYKEY(`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=MyISAMDEFAULTCHARSET=latin1;