Advertisement
gocha

Read EventLog(Win)/Syslog(*nix) in One Command

May 15th, 2013
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.22 KB | None | 0 0
  1. # 謎のコマンド ostype は uname を使ってなんとかすべし。
  2. # Windows 環境下での uname の戻り値は環境差がきっと大きいです。
  3. # あと、PS1_GET_EVENTLOG_OPT も需要に応じて適当に変更するとよし。
  4. # Windows で nkf を使っている部分も環境に応じて調整するよろし!!
  5. SYSLOG=/var/log/messages
  6.  
  7. # get application log output (*nix => syslog, windows => event log)
  8. #   -f <logfile>    specify log file name (*nix only)
  9. #   -n <count>      output the latest <count> lines
  10. #   -m <word>       output the lines which contains the specified (alphanumeric) word in message
  11. # more filters can be applied by external command such as grep, cut, etc.
  12. #
  13. # Requirements:
  14. #   Windows: PowerShell 2.0 or later
  15. getaplog()
  16. {
  17.   OPT_LOGPATH=$SYSLOG
  18.   OPT_WORDINCL=""
  19.   OPT_LINECOUNT=""
  20.   OPT_ERROR=0
  21.  
  22.   OPTIND_OLD=$OPTIND
  23.   OPTIND=1
  24.   while getopts "f:m:n:" OPT; do
  25.     case $OPT in
  26.       f) OPT_LOGPATH="$OPTARG";;
  27.       m) OPT_WORDINCL="$OPTARG";;
  28.       n) OPT_LINECOUNT="$OPTARG";;
  29.       ?) return 1;;
  30.     esac
  31.   done
  32.   shift $(($OPTIND - 1))
  33.   OPTIND=$OPTIND_OLD
  34.  
  35.   if [ `ostype` = "Windows" ]; then
  36.     #PS1_GET_EVENTLOG_OPT="Application -Source XXX, YYY"
  37.     PS1_GET_EVENTLOG_OPT="Application"
  38.     if [ ! -z "$OPT_WORDINCL" ]; then
  39.       PS1_GET_EVENTLOG_OPT="$PS1_GET_EVENTLOG_OPT -Message \"*$OPT_WORDINCL*\""
  40.     fi
  41.     if [ ! -z "$OPT_LINECOUNT" ]; then
  42.       PS1_GET_EVENTLOG_OPT="$PS1_GET_EVENTLOG_OPT -Newest $OPT_LINECOUNT"
  43.     fi
  44.  
  45.     yes "" | powershell -Command "\$OutputEncoding = [console]::OutputEncoding;" Get-EventLog $PS1_GET_EVENTLOG_OPT "| Sort-Object TimeGenerated | foreach { Write-Host (\$_.TimeGenerated.ToString('yyyy/MM/dd HH:mm:ss') + ' ' + \$_.MachineName + ' ' + \$_.Source + ': ' + \$_.Message) }" 2>/dev/null | nkf -s -w8
  46.   else
  47.     if [ ! -f "$OPT_LOGPATH" ]; then
  48.       echo "getaplog: ${OPT_LOGPATH} file not exist" 2>&1
  49.       return 1
  50.     fi
  51.  
  52.     # lazy wildcard => regex conversion
  53.     OPT_WORDINCL=`echo "$OPT_WORDINCL" | sed -e s/*/.*/g`
  54.  
  55.     if [ ! -z "$OPT_LINECOUNT" ]; then
  56.       tail "-$OPT_LINECOUNT" $OPT_LOGPATH | grep "$OPT_WORDINCL"
  57.     else
  58.       grep "$OPT_WORDINCL" $OPT_LOGPATH
  59.     fi
  60.   fi
  61.   return 0
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement