Chinaunix首页 | 论坛 | 博客
  • 博客访问: 68657
  • 博文数量: 15
  • 博客积分: 841
  • 博客等级: 准尉
  • 技术积分: 180
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 00:14
文章分类

全部博文(15)

文章存档

2011年(1)

2008年(14)

我的朋友

分类: 系统运维

2008-06-18 07:18:45

发现一些乱七八糟的东西,备查...
 
1.[JavaScript]好像是读XML文件的!
 
/* Records.xml */


 
2.[Shell]UNIX下的几个正则,好像是个半成品!成品不知道去那了!
#!/usr/bin/sh
#################################################################################
#init parameters
ROOT_DIR={/source>/dest>ftp:fpt@127.0.0.1:23/ftpdest}
SUB_DIR_NAME={APP1:APP2:APP3}
UNIX_DIR=unix
#################################################################################
##Environment variables
PATH=.:/usr/bin:/usr/ccs/bin:/usr/contrib/bin export PATH
#################################################################################
APPDIR=`echo $APPDIR|sed 's/:/ /g'`
for APP in $APPDIR
do
 if [ -d $ROOTDIR/$APP ]
 then
   echo [Y] $ROOTDIR/$APP
 else
   echo [N] $ROOTDIR/$APP
   FLAG=1
 fi
done
if [ $FLAG ]
then
 while true
 do
  echo "有不存在目录,是否继续[Y/N]:\c"
  YN=`dd if=/dev/tty bs=2 count=1 2>/dev/null`
  YN=`echo $YN|sed 'y/yn/YN/'`
  if [ "$YN" = "Y" ]
  then
   break
  fi
 done
fi
 
#cat go|sed -e 's/[  ].*//' -e 's/^[^0-9a-zA-Z_]*//' #取go文件中的名称
#awk '/-o/' solaris9.mk|sed -e '/\.o/d' -e 's/^.*-o *//g' -e 's/ .*$//' -e 's/\/[^/]*$//g' #取应用程序目录
#awk '/-o/' makefile|sed -e '/\.o/d' -e 's/^.*-o *//g' -e 's/ .*//' -e 's/[^\/]*\///' #取应用程序名称
#ps -ef|grep TEST|sed -e '/grep /d' -e 's/^ *//' -e 's/^[^ ]*//' -e 's/^ *//' -e 's/ .*//' #根据名称取PID
#ps -ef|grep APP|sed -e '/grep /d'|awk '{print $2}' #取PID
#awk '/^[  ]*OBJDIR[  ]*?=/' makefile|sed -e 's/.*=//' -e 's/[  ]*//' -e 's/[  ].*//' #根据$(%%%)取名称
3.[Shell]HP-UX下用glance收集信息
#!/bin/sh
# =============================================================
# Script Name: glance_collect
# File Name : glance_collect.sh
# =============================================================
# REVISION HISTORY:
# DATE          WHO   Description
# 20061102 aowken   create
# =============================================================
SCRIPT_HOME="/command/collect"
SCRIPT_NAME="glance_collect"
SYNTAX_FILE=$SCRIPT_HOME/"proc.syntax"
LOG_FILE=$SCRIPT_HOME/"stat/report.`date +%Y%m%d.%a`"
INTERVAL=300
ITERATION=1
GLANCE_CMD="/opt/perf/bin/glance -adviser_only -syntax $SYNTAX_FILE -j $INTERVAL -iterations $ITERATION"
/usr/bin/clear
# =============================================================
# glance_collect script.
# Note: Since the data collection is in $(SCRIPT_HOME)/stat
# =============================================================
 $GLANCE_CMD 2>/dev/null >> $LOG_FILE
# =============================================================
# End of glance_collect script.
# =============================================================
 
 
PRINT "SYNTAX FILE: glance.syntax"
PRINT "=============================================================="                
PRINT "[G][",gbl_stattime,"] ","S: ",gbl_mem_sys|6," U: ",gbl_mem_user|6," B: ",gbl_mem_cache|6," F: ",gbl_mem_free|6," T: ",gbl_mem_phys|6
PRINT "--------------------------------------------------------------"                               
root_total_mem_res = 0  
oracle_total_mem_res = 0
hisun_total_mem_res = 0
other_total_mem_res = 0             
PROCESS LOOP
IF proc_state == "active" THEN
{
PRINT "[",gbl_stattime,"] ",proc_user_name," ",proc_proc_id|6," ",proc_mem_res/1024|6|2,"mb ",proc_thread_count," ",proc_proc_name               
IF proc_user_name == "root" THEN                                            
root_total_mem_res = root_total_mem_res + proc_mem_res 
ECLE IF proc_user_name == "oracle" THEN                                            
oracle_total_mem_res = oracle_total_mem_res + proc_mem_res                       
ELSE IF proc_user_name == "USER" THEN
hisun_total_mem_res = hisun_total_mem_res + proc_mem_res 
ELSE
other_total_mem_res = other_total_mem_res + proc_mem_res
}         
PRINT "``````````````````````````````````````````````````````````````"                
PRINT "[",gbl_stattime,"] R:",root_total_mem_res/1024|6|2,"mb  O:",oracle_total_mem_res/1024|6|2,"mb  H:",hisun_total_mem_res/1024|6|2,"mb  E:",other_total_mem_res/1024|6|2                                
3.[SHELL]killme 杀进程用的
##########################################################################
# @ - killme
#
# purpose: kill one process by name
#
# desc: auto get process name in [go] file, but only first non-blank line in.
#    kill it one by one if N processes have the same name.
#
# os: hp-ux,solaris,redhat
# v0.1,power by
##########################################################################
#!/usr/bin/sh
FILE_NAME=go
APPNAME=`cat go|sed -e '/^[  ]*$/d'` #delete blank-line
APPNAME=`echo $APPNAME|sed -e 's/^[  ]*//' -e 's/.*\///' -e 's/^[  ].*//' -e 's/[  ].*$//'` #blank at begin,path,blank at begin,blank at begin to $
if [ "$APPNAME" = "" ]
then
 echo "get application name failed in (${FILE_NAME})."
 exit 0
fi
PIDS=`ps -ef|grep ${USER}|grep ${APPNAME}|sed -e '/grep /d' -e 's/^[  ]*//' -e 's/^[^ ]*//' -e 's/^[  ]*//' -e 's/[  ].*//'|sort -n`
#PIDS=`echo ${PID}|sed -e 's/[  ].*//'`
if [ "$PIDS" != "" ]
then
 for PID in $PIDS
 do
  if [ "$PID" != "" ]
  then
   kill $PID
   sleep 3
   echo "-----Kill ${APPNAME}(${PID}) done. :)"
  fi
 done
else
 echo "get process(${APPNAME}) PID failed."
 exit 0
fi
exit 0
#
 
4.[PHP+MYSQL]PHP使用adodb访问MYSQL,好烂的代码,哈哈!
require_once('config.php');
require_once('adodb/adodb.inc.php');
class DB
{
 var $conn = null;
 function __construct() {
  try {
   $this->conn = &ADONewConnection(__DB_TYPE);
   $this->conn->Connect(__DB_HOST,__DB_USER,__DB_PASSWORD,__DB_NAME) or die('Server too busy. Please retry in 10 seconds.');
   $this->conn->debug = !__RELEASE_VERSION;
   $this->conn->SetFetchMode(ADODB_FETCH_ASSOC);
  } catch (Exception $e) { }
 }
 function __destruct() {
  try {
   $this->conn->Disconnect();
   $this->conn = null;
  } catch (Exception $e) { }
 }
 #Purpose: verify account
 #Desc: verify general account is default,must set $Admin is true where want to verify admin account.
 #Reture: true/false
 function VerifyAccount($UserName, $Password, $Admin = false) {
  if( $Admin )
   return !$this->Execute("call P_Pay_VerifyAdmin('$UserName','$Password',@v_result)");
  else
   return !$this->Execute("call P_Pay_VerifyUser('$UserName','$Password',@v_result)");
 }
 #Purpose: register account
 #Desc: register general account is default,must set $Admin is true where want to register admin account.
 #Reture: true/false
 function RegisterAccount($EMail, $Password, $FirstName, $LastName, $MobilePhone, $LandingPhone,
      $Country = null, $City = null, $Address = null, $ZipCode = null, $IPAddress = null, $Recommender = null, $Admin = false) {
  if( $Admin )
   return !$this->Execute("call P_Pay_RegisterAdmin('$EMail', '$Password', '$FirstName', '$LastName',
   '$MobilePhone', '$LandingPhone', @v_result)");
  else
   return !$this->Execute("call P_Pay_RegisterUser('$EMail', '$Password', '$FirstName', '$LastName', '$MobilePhone', '$LandingPhone',
        '$Country','$City', '$Address', '$ZipCode', '$IPAddress', '$Recommender', @v_result)");
 }
 #Purpose: register account
 #Desc: modify general account is default,must set $Admin is true where want to modify admin account.
 #Return: true/false
 function ModifyAccount($OpUser, $OpRemark, $OpIPAddress, $EMail, $Password, $NewPassword, $FirstName, $LastName,
       $MobilePhone, $LandingPhone, $Country, $City, $Address, $ZipCode, $Admin = false) {
  if( $Admin )
   return !$this->Execute("call P_Pay_ModifyAdmin('$OpUser', '$OpRemark', '$OpIPAddress', '$EMail', '$Password', '$NewPassword',
      '$FirstName', '$LastName', '$MobilePhone', '$LandingPhone', @v_Result)");
  else
   return !$this->Execute("call P_Pay_ModifyUser('$OpUser', '$OpRemark', '$OpIPAddress', '$EMail', '$Password', '$NewPassword',
      '$FirstName', '$LastName', '$MobilePhone', '$LandingPhone', '$Country', '$City', '$Address', '$ZipCode', @v_Result)");
 }
 
 #############################################################################
 #currency info
 function GetCurrencyInfo() {
  $rs = $this->Execute('SELECT CODE, FULLNAME, SHORTNAME, SYMBOL, RATE, STATUS FROM PAY_CURRENCYINFO ORDER BY CODE');
  $arrCurrency = array();
  while(!$rs->EOF) {
   array_push($arrCurrency, array('Code'=>$rs->fields['CODE'],'FullName'=>$rs->fields['FULLNAME'],'ShortName'=>$rs->fields['ShortName'],
         'Symbol'=>$rs->fields['SYMBOL'],'Rate'=>$rs->fields['RATE'],'Status'=>$rs->fields['STATUS']));
   $rs->MoveNext();
  }
  return $arrCurrency;
 }
 function AddCurrency($FullName,$ShortName,$Symbol,$Rate, $Status) {
  $this->Execute("INSERT INTO PAY_CURRENCYINFO VALUES(NULL, '$FullName', '$ShortName','$Symbol','$Rate',$Status)");
  return true;
 }
 function ModifyCurrency($Code, $FullName,$ShortName,$Symbol,$Rate, $Status) {
  $this->Execute("UPDATE PAY_CURRENCYINFO SET FULLNAME = $FullName, SHORTNAME=$ShortName,
      SYMBOL=$Symbol, RATE=$Rate, STATUS=$Status WHERE CODE = $Code");
  return true;
 }
 function DeleteCurrency($Code) {
  $this->Execute("UPDATE PAY_CURRENCYINFO SET STATUS=3 WHERE CODE=$Code");
  return true;
 }
 #######################################################################################
 #Game
 function GetGameInfo() {
  $rs = $this->Execute('SELECT CODE, PIC_1, PIC_2, NAME, STATUS FROM PAY_GAME ORDER BY CODE');
  $arrGame = array();
  while (!$rs->EOF) {
   array_push($arrGame, array('Code'=>$rs->fields['CODE'], 'PIC_1'=>$rs->fields['PIC_1'], 'PIC_2'=>$rs->fields['PIC_2'] ,'Name'=>$rs->fields['NAME'], 'Status'=>$rs->fields['STATUS']));
   $rs->MoveNext();
  }
  return $arrGame;
 }
 function AddGame($GameName, $PIC_1, $PIC_2, $Status) {
  $this->Execute("INSERT INTO PAY_GAME VALUES(NULL, $GameName,$PIC_1,$PIC_2,$Status)");
  return true;
 }
 function ModifyGame($Code, $GameName) {
  $this->Execute("UPDATE PAY_GAME SET NAME = $GameName WHERE CODE=$Code");
  return true;
 }
 function DeleteGame($Code) {
  $this->Execute("UPDATE PAY_GAME SET STATUS = 3 WHERE CODE=$Code");
  return true;
 }
 
 #admin menu
 function getAdminMenu() {
  $rs = $this->Execute('select ModuleID,ModuleName, MenuID, MenuName, MenuURL from pay_adminmenu order by moduleid, MenuID');
  $arrModule = array();
  $arrMenu = array();
  $ModuleID = null;
  $ModuleName = null;
  while(!$rs->EOF) {
   if( $rs->fields['ModuleID'] != $ModuleID ) {
    if( ($rs->CurrentRow()!=0) ) {
     array_push($arrModule, array('ModuleID' => $ModuleID, 'ModuleName' => $ModuleName, 'Menu' => $arrMenu));
     $arrMenu = array();
    }
    $ModuleID = $rs->fields['ModuleID'];
    $ModuleName = $rs->fields['ModuleName'];
   }
   array_push($arrMenu, array('MenuID' => $rs->fields['MenuID'], 'MenuName' => $rs->fields['MenuName'], 'MenuURL' => $rs->fields['MenuURL']));
   $rs->MoveNext();
  }
  array_push($arrModule, array('ModuleID' => $ModuleID, 'ModuleName' => $ModuleName, 'Menu' => $arrMenu));
  return $arrModule;
 }
 #Purpose: execute SQL/PROC
 #Desc: return original value(non-process) if $sql is any SQL or PROC only one out parameter.
 #  return result set if PROC hava N out parameters,but $out must is true
 #  and it return succeed only.
 #Return: true/false/ResultSet
 function & Execute($sql, $out = false, $inputarr = false) {
  try {
   if( strtoupper(substr(ltrim($sql),0,4)) != 'CALL' )
    return $this->conn->Execute($sql,$inputarr);
   else
   {
    $this->Execute('set @v_result;');
    $this->conn->Execute($sql,$inputarr);
    $rs = $this->Execute('select @v_result');
    
    if( $out == false )
     return $rs->fields['@v_result'];
    elseif( $out && !$rs->fields['@v_result'] )
     return $rs;
    else
     return false;
   }
  } catch (Exception $e) { }
 }
}
?>
 
5.[PHP]smarty的filter,好像是修正路径用的!
function smarty_prefilter_fixpath($tpl_source,&$smarty)
{
    $temp = preg_replace("/((?<=[\"\'\(])(([\.\/]*?)[\w\/-]+?\.gif|([\.\/]*?)[\w\/-]+?\.jpg|([\.\/]*?)[\w\/-]+?\.css)(?=[\"\'\)]))/",
    __THEMES_DIR."$1",$tpl_source);
    return preg_replace("/\.\.\//",'',$temp);
}
 
6.[PHP]好像是产生随机字符串的!
function randString($size = 20)
{
    $time = time();
    $str = '11';
   
    for ($i = 0; $i < $size; $i++)
    {
        srand($time);
        $time = mt_rand(97, 122);
        $str .= chr($time);
    }
    return $str;
}
define(__RANDSRC,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-----_____,,,,,');
function randCmd($cmd=null, $size = 64) {
 $str = '';
 for($pos = 0,$i=0; $i<$size; $i++) {
  $shuffleStr = str_shuffle(__RANDSRC);
  $str .= $shuffleStr[mt_rand(0, strlen(__RANDSRC))];
 }
 $_SESSION[$str]=$cmd;
 return $str;
}
?>
 
7.[MFC]Dialog上放PropertySheet需要设置WS_EX_CONTROLPARENT样式
8.[MFC]取interface地址
void GetInterfaceAddress(char * ipAddress)
{
 PIP_ADAPTER_INFO pAdapterInfo;
 PIP_ADAPTER_INFO pAdapter = NULL;
 DWORD dwRetVal = 0;
 ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO)*16;
 
 pAdapterInfo = (IP_ADAPTER_INFO *) new byte[ulOutBufLen];
 
 if (GetAdaptersInfo( pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
  delete [] pAdapterInfo;
  pAdapterInfo = (IP_ADAPTER_INFO *) new byte[ulOutBufLen];
 }
 
 if ((dwRetVal = GetAdaptersInfo( pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
  pAdapter = pAdapterInfo;
  while(pAdapter)
  {
   if(pAdapter->Index == m_item.dwForwardIfIndex)
   {
    strcpy(ipAddress, pAdapter->IpAddressList.IpAddress.String);
    delete [] pAdapterInfo; 
    return;
   }
   pAdapter = pAdapter->Next;
  }
 }
 delete [] pAdapterInfo; 
 return;
}
 
9.[MFC]取路由表
PMIB_IPFORWARDTABLE GetRouteTable()
{
 PMIB_IPFORWARDTABLE pIpForwardTable;
 DWORD dwSize = sizeof(MIB_IPFORWARDTABLE)*64;
 DWORD dwRetVal = 0;
 
 pIpForwardTable =  (PMIB_IPFORWARDTABLE) new byte[dwSize];
 if (GetIpForwardTable(pIpForwardTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
  delete [] pIpForwardTable;
  pIpForwardTable = (PMIB_IPFORWARDTABLE) new byte[dwSize];
 }
 
 if ((dwRetVal = GetIpForwardTable(pIpForwardTable, &dwSize, 0)) != NO_ERROR) {
  TRACE("\tGetIpForwardTable failed.\n");
  delete [] pIpForwardTable;
  pIpForwardTable = NULL;
 }
 
 return pIpForwardTable;
}
 
10.[VC++]估计是监视进程用的,写的感觉怪怪的
// ProcMon.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
#include
#include "psapi.h"
#pragma comment(lib, "psapi.lib")
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
void GetDateTime(char * pDateTime);
BOOL WINAPI ConsoleRoutine(DWORD dwCtrlType);
BOOL GetProcessName( DWORD processID, TCHAR * lpszProcessName);
int main(int argc, char* argv[])
{
 HANDLE hProc =  GetCurrentProcess();
 SetPriorityClass(hProc, 0x00004000); // BELOW_NORMAL_PRIORITY_CLASS  
 
 SetConsoleCtrlHandler(ConsoleRoutine, true);
 system("title  ProcessMonitor v0.1 by ");
 //----------------------------------------------------------------
 FILE *stream;
 int nProcNum = 0;
 char ProcList[32][MAX_PATH];
 int i, j;
 char szBuffer[MAX_PATH];
 char szDateTime[32];
 char ActiveProc[128][MAX_PATH];
 DWORD aProcesses[1024], cbNeeded, cProcesses;
 //----------------------------------------------------------------
 switch(argc) {
 case 1:
  break;
 case 2:
  if (strcmp(argv[1], "-h")==0||strcmp(argv[1], "-H")==0||strcmp(argv[1], "/?")==0)
  {
   printf("监控 Proclist.txt 文件列表中的进程\n\n");
   printf("ProcMon [-d name] [-f filename]\n\n");
   
   printf("\t-d\t将系统中的所有映像文件在Driver盘的进程写入文件。\n");
   printf("\t-f\t产生的配置文件名称。\n\n");
   printf("Example: ProcMon -driver d: -config Proclist.txt\n");
  }
  return 0;
 case 5:
  if (strcmp(argv[3], "-f")==0||strcmp(argv[3], "-F")==0)
  {
   stream = fopen(argv[4],"a");
   
   if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    return 0;
   
   // Calculate how many process identifiers were returned.
   
   cProcesses = cbNeeded / sizeof(DWORD);
   
   for ( i = 0, j=0; i < cProcesses; i++)
   {
    if(GetProcessName( aProcesses[i], szBuffer))
    {
     if (tolower(argv[2][0]) == tolower(szBuffer[0]))
     {
      fputs(szBuffer,stream);
      fputs("\n",stream);
      printf(szBuffer);
     }
    }
   }
   
   fclose(stream);
   printf(" Create config file OK!\n");
  }
  return 0;
 default:
  printf("参数的数量不正确。\n");
  return 0;
 }
 //----------------------------------------------------------------  
 if( (stream = fopen("Proclist.txt", "r" )) != NULL )
 {
  while(fgets(ProcList[nProcNum], MAX_PATH, stream) != NULL)
  {
   if(ProcList[nProcNum][strlen(ProcList[nProcNum])-1]=='\n')
    ProcList[nProcNum][strlen(ProcList[nProcNum])-1] = 0;
    
   nProcNum++;
  }
  fclose( stream );
 } else {
  printf("was not found Proclist.txt\n" );
 }
 
 //----------------------------------------------------------------
 while (TRUE)
 {
  if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
   return 0;
  
  // Calculate how many process identifiers were returned.
  
  cProcesses = cbNeeded / sizeof(DWORD);
  
  for ( i = 0, j=0; i < cProcesses; i++)
   if(GetProcessName( aProcesses[i], ActiveProc[j]))
    j++;
  cProcesses = j;
  for ( i = 0; i < nProcNum; i++ )
   for ( j = 0; j < cProcesses; j++)
    if (strcmp(ProcList[i], ActiveProc[j]) == 0)
     break;
    else
     if (j == cProcesses-1)
     {
      Sleep(30000);
      stream = fopen("run.log","a");
      GetDateTime(szDateTime);
      if(WinExec(ProcList[i], SW_SHOWNORMAL) < 32)
       sprintf(szBuffer, "%s%s%s\n", szDateTime, "Run ", ProcList[i], "FAILED.");
      else
       sprintf(szBuffer, "%s%s%s\n", szDateTime, "Run ", ProcList[i]);
      printf(szBuffer);
      fputs(szBuffer, stream);
      fclose(stream);
      break;
     }
  Sleep(60000);
 }
 return 0;
}
BOOL WINAPI ConsoleRoutine(DWORD dwCtrlType)
{
 if (dwCtrlType == CTRL_C_EVENT ||
  dwCtrlType == CTRL_BREAK_EVENT ||
  dwCtrlType == CTRL_CLOSE_EVENT ||
  dwCtrlType == CTRL_SHUTDOWN_EVENT)
 {
  ExitProcess(0);
  return true;
 }
 return false;
}
BOOL GetProcessName( DWORD processID, TCHAR * lpszProcessName)
{
 TCHAR szProcessName[MAX_PATH] = TEXT("");
 // Get a handle to the process.
 
 HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
  PROCESS_VM_READ,
  FALSE, processID );
 
 // Get the process name.
 
 if (NULL != hProcess )
 {
  HMODULE hMod;
  DWORD cbNeeded;
  
  if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
   &cbNeeded) )
  {
   GetModuleFileNameEx( hProcess, hMod, szProcessName,
   sizeof(szProcessName)/sizeof(TCHAR) );
  }
 }
  
 CloseHandle( hProcess );
 
 if(strcmp(szProcessName, "") == 0)
  return FALSE;
 else
 {
  strcpy(lpszProcessName, szProcessName);
  return TRUE;
 }
}
void GetDateTime(char * pDateTime)
{
 time_t t_cur = time(0);
 tm* tm_cur = localtime(&t_cur);
 strftime(pDateTime, 32, "[%Y-%m-%d %H:%M:%S] ", tm_cur);
 return;
}
 
11.[MYSQL]存储过程调用方式
set @v_result = null;
call P_TEST('654321','123456',@v_result);
select @v_result;
阅读(1262) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~