Linux monitoring

From Essential
Revision as of 22:35, 3 April 2023 by Tcepo (talk | contribs) (→‎monitor.sh)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Writting activity

monitor.sh <filter>

apt install lsof -y ||yum install lsof -y

MyBin="monitor.sh"

>~/$MyBin
chmod 755 ~/$MyBin
cat <<EOT >>~/$MyBin
#!/bin/bash
# ynotopec at gmail.com

if [ -z "\$@" ] ;then
  MyKey="-ie crit\|err\|warn\|fail\|denie"
else
  MyKey="\$@"
fi
MyBin="\$(basename \$0)"

#seconds timeout
MyTimeOutMin=\$((15*60))
MyTimeOutMax=\$((60*60))

# bash colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# 3 derniers jours du mois ou 9h à 17h en jour ouvré
if [ \$(date +%d -d "3 day") -lt \$(date +%d) ] || { [ \$(date +%H) -ge 9 ] && [ \$(date +%H) -lt 17 ] && [ \$(date +%u) -lt 6 ] ;} ;then
  MyTimeOut=\$MyTimeOutMin
else
  MyTimeOut=\$MyTimeOutMax
fi

logList=~/\${MyBin}.cfg

(find -L /var/log -type f -mmin -\$((\${MyTimeOut}/60))
lsof -X 2>/dev/null |sed -rn 's#^.*[[:space:]]+[0-9]+w[[:space:]]+REG[[:space:]]+[^/]+(.*)#\1#p' ) \
  |grep -v /var/log/lastlog |grep -v "\${logList}" |sort -u |while read lineMy ;do
  find "\${lineMy}" -type f -mmin -\$((\${MyTimeOut}/60)) 2>/dev/null
done >"\${logList}"

MyCacheFile="/tmp/\${MyBin}.\$\$"

function MyStep1 {
>\${MyCacheFile}

# 3 derniers jours du mois ou 9h à 17h en jour ouvré
if [ \$(date +%d -d "3 day") -lt \$(date +%d) ] || { [ \$(date +%H) -ge 9 ] && [ \$(date +%H) -lt 17 ] && [ \$(date +%u) -lt 6 ] ;} ;then
  MyTimeOut=\$MyTimeOutMin
else
  MyTimeOut=\$MyTimeOutMax
fi

cat ~/\${MyBin}.cfg |while read MyLogPath ;do
  if [ -f "\$MyLogPath" ] ;then
    MyLogElapsed=\$((\$(date +%s) - \$(date +%s -r "\$MyLogPath")))

    if [ "\$MyLogElapsed" -lt "\$MyTimeOut" ] ;then
      MyResult="\$(tail -111 "\$MyLogPath" 2>/dev/null |grep -aoE '[[:print:]]{4,}' |grep \$MyKey |tail -2 |cut -c1-111)"
      if [ -z "\$MyResult" ] ;then
        MyResult="\$(tail -2 "\$MyLogPath" 2>/dev/null |grep -aoE '[[:print:]]{4,}' |tail -1 |cut -c1-111)"
        if [ ! -z "\$MyResult" ] ;then
          echo -e "\${NC}== \$MyLogPath ==" >>\${MyCacheFile}
          echo -e "\${GREEN}\${MyResult}\${NC}" >>\${MyCacheFile}
        fi
      else
        echo -e "\${NC}== \$MyLogPath ==" >>\${MyCacheFile}
        echo -e "\${RED}\${MyResult}\${NC}" >>\${MyCacheFile}
      fi
    fi
  fi
done
}

MyStep1
cat \${MyCacheFile} |grep -v -w -f ~/\${MyBin}.cfg >~/\${MyBin}.ref

while true ; do
  MyStep1
  diff --changed-group-format='%>' --unchanged-group-format='' ~/\${MyBin}.ref \${MyCacheFile} |\
    awk -v titleStart="\${NC}==" '{if (\$1 == titleStart)
           title=\$0 ;
         else
           {if (title != "")
             print title ;
           title="" ;
           print \$0 ;}}' >\${MyCacheFile}.diff
  clear
  cat \${MyCacheFile}.diff
  sleep 3
done
EOT

#kill -9 $$

test

~/monitor.sh