Instruktaż/Tutorial Logman Collector - Monitorowanie aktywności serwera (Gadu-Gadu lub Log4Net/nLog)

Silas Mariusz

Silas Mariusz

rm -rf /
Help us, GOD!
5 Kwiecień 2008
10 173
31
2 250
153
39
Nowy Sącz
forum.qnap.net.pl
QNAP
TS-x77
Ethernet
1 GbE

Logman Collector

LogMan Collector to program umożliwiający monitorowanie w czasie rzeczywistym dziennika zdarzeń (logów) serwera QNAP NAS i przekazywanie aktywności za pośrednictwem sieci Gadu-Gadu.

Upload 2014 11 2 19 57 53

Upload 2014 11 2 19 58 32


Monitorowane informacje
  • (Connection Logs) aktywność połączeń systemowych/operacji usług sieciowych na plikach
  • (Event Logs) zdarzenia systemowe
  • dla aplikacji drugich: inne powiadomienia z pliku announce.out po otrzymaniu sygnału SIGHUP
Metody przekazywania
  • Gadu-Gadu Bot (lub dowolny inny zewnętrzny skrypt PHP wywoływany zapytaniem http..)
czytelne formatowanie wiadomości W przypadku korzystania z usługi Gadu-Gadu za pomocą klienta wtw.im/ zalecena zainstalowanie wtyczki [wtwBIU] Formatowanie wiadomości wysyłanych dla lepszej czytelności przekazywanych informacji.


Jak zainstalować?
  1. Pobierz i zainstaluj Gadu-Gadu
    Wtw
    Alternatywnie do Gadu-Gadu czy AQQ, zainstaluj komunikator WTW. (Pobierz ze strony: WTW.im)

  2. Zainstaluj Entware
    Optware vs qnapware
    Zaloguj się do panelu zarządzania QNAP i z App Center zainstaluj Entware. Do pobrania z zasobów forum.

  3. Włącz logowanie połączeń
    Qnap system logs start logging
    Aby monitorować zdarzenia usług plików, przejdź do logów zdarzeń i włącz logowanie połączeń.

  4. Dodaj nowy kontakt bota Logman #51816153
    Qnap wtw dodaj nowy kontakt
    Do Gadu-Gadu dodaj nowy kontakt o numerze: 51816153 i podpisz np. Logman

  5. Potwierdź swój numer Gadu-Gadu
    Qnap logman subscribe
    Napisz do bota Logman #51816153 wiadomość: ZAPISZ - (pamiętaj! DUŻE litery). W ten sposób autoryzujesz swój numer Gadu-Gadu i potwierdzisz chęć otrzymywanie wiadomości.

  6. Połącz się na konsolę shell po SSH serwerem QNAP
    Putty host name
    Za pomocą programu PuTTY połącz się po SSH z serwerem QNAP. (Uwaga: Upewnij się, że w panelu zarządzania QNAP włączyłeś usługę SSH!)

  7. Zaloguj jako admin
    Putty login as admin
    Użyj poświadczeń administratora, aby zalogować się na serwer. (Notka dla początkujących: Wprowadzanie hasła jest ukryte - kursor nie zmienia swojej pozycji.)

  8. Pobierz program Logman
    Qnap logman download
    Wpisz poniższą linijkę, aby pobrać program Logman:
    Bash:
    wget https://files.qnap.net.pl/repo/pool/projects/tools/logman/releases/last/logman.sh

  9. Nadaj uprawnienia pliku wykonywalnego
    Qnap logman chmod plus x
    Aby móc uruchomić pobrany plik, nadaj mu odpowiednie uprawnienia zezwalające na jego uruchomienie. W tym celu wpisz:
    Bash:
    chmod +x logman.sh

  10. Zainstaluj...
    Qnap logman install
    Rozpocznij łatwą instalacje programu wykonując polecenie:
    Bash:
    ./logman.sh install

  11. Podaj swój numer Gadu-Gadu
    Qnap logman gadu gadu im number
    Podaj docelowy numer Gadu-Gadu, na który chcesz otrzymywać logi z serwera QNAP.
    (Potwierdzony do otrzymywania wiadomości w kroku 5)

  12. Koniec
    Logman installation successful
    Od teraz na bieżąco będziesz informowany o operacjach serwera QNAP.
W terminalu... - Instalacja
Link: https://asciinema.org/a/87681


Konfiguracja dodatkowa
  • Ignorowanie logów od określonych użytkowników lub zawierających treść

    Aby ignorować wiadomości log zawierające określoną treść lub pochodzące od określonego użytkownika w katalogu, w którym zainstalowany jest logman umieść odpowiednio pliki:
    • ignore.lst - zawierający ignorowane słowa (w każdej linii osobno)
    • ignore.usr - zawierający ignorowanych użytkowników (w każdej linii osobno)

    np.
    ignore.lst napisał:
    Public/Music
    Music/
    Pool/Movies
    ignore.usr napisał:

  • Wyświetlanie nazwy Hostname komputerów w logach zamiast adresu IP
    Qnap logman hostname instead ip addr

    Aby dla komputerów znajdujących się w sieci lokalnej wyświetlana była łatwa do identyfikacji nazwa hosta zamiast adresu IP określ swoją podsieć w pliku config.ini.


    W tym celu wykonaj poniższe polecenia:
    1. Określ pule adresową komputerów Twojej sieci LAN komendą:
      lan_subnet=192.168.1.
      (format: x . x . x . )
      Qnap logman hostname instead ip addr

    2. Znajdź katalog, do którego został zainstalowany program Logman
      Bash:
      publicdir=`/sbin/getcfg Public path -f /etc/config/smb.conf`
      qpkgdir=`cd $publicdir && cd ../.qpkg/ && pwd`
      installdir="$qpkgdir/logman"

    3. Wyświetl obecny plik config.ini
      cat "$installdir/config.ini"

    4. Zapisz nową wartość pola local_subnet w pliku config.ini wykonując polecenie:
      Bash:
      setcfg Network local_subnet "$lan_subnet" -f "$installdir/config.ini" -c

    5. Upewnij się, że wartość pola local_subnet w pliku config.ini została zmieniona
      getcfg Network local_subnet -f "$installdir/config.ini"

    6. Zrestartuj program Logman
      /etc/init.d/logman.sh restart
W terminalu... - Konfiguracja dodatkowa


Ciekawostki
  • Wykonanie testu przez dodanie nowego wpisu w logach połączeń (logowanie połączeń musi być włączone)
    Bash:
    conn_log_tool -t0 -ulogman -p127.0.0.1 -mlocalhost -i0 -n0 -a "Ja jestem Pan Tik-Tak"

  • SMS/info z środowiska chroot dla rtorrent - na własną odpowiedzialność: [Bash] logman - Pastebin.com

  • Jak Logman wygląda z poziomu konsoli shell serwera?
    Logman console i1 Logman console i2

    W terminalu... - Widok logmanowego workera
    Link: https://asciinema.org/a/87689
 
Dla komunikacji Debian (chroot) -> QTS potrzebujemy dodać kilka rzeczy w QPKG Debiana i w samym Debianie:
QPKG debiana .qpkg/debian6/debian6.sh
odnaleźć
Bash:
mount_deb(){
...
  mount -o bind /dev $DEB_BASE/dev
  mount -o bind /dev/pts $DEB_BASE/dev/pts
  mount -o bind /sys $DEB_BASE/sys
#  mount -o bind /dev $DEB_BASE/env/wheezy/dev
...

dopisać
Bash:
mount -o bind /tmp $DEB_BASE/tmp.qnap

zamienić całą sekcję
Bash:
umount_deb(){
  umount $DEB_BASE/mnt/ext/home 2> /dev/null
  umount $DEB_BASE/mnt/ext 2> /dev/null
  umount $DEB_BASE/mnt/HDA_ROOT 2> /dev/null
  umount $DEB_BASE/share/Public 2> /dev/null
  umount $DEB_BASE/share/Web 2> /dev/null
  umount $DEB_BASE/share/Multimedia 2> /dev/null
  umount $DEB_BASE/share/Usb 2> /dev/null
  umount $DEB_BASE/share/Download 2> /dev/null
  umount $DEB_BASE/share/Recordings 2> /dev/null

  umount $DEB_BASE/sys
  umount $DEB_BASE/tmp.qnap
  umount $DEB_BASE/proc
  umount $DEB_BASE/dev/pts
  umount $DEB_BASE/dev

#  umount $DEB_BASE/env/wheezy/sys
#  umount $DEB_BASE/env/wheezy/proc
#  umount $DEB_BASE/env/wheezy/dev/pts
#  umount $DEB_BASE/env/wheezy/dev

  if test $? -ne 0
  then
  /bin/sleep 5
  umount $DEB_BASE/sys 2>&-
  umount $DEB_BASE/proc 2>&-
  umount $DEB_BASE/dev/pts 2>&-
  umount $DEB_BASE/dev 2>&-
  umount $DEB_BASE/tmp.qnap 2>&-

#  umount $DEB_BASE/env/wheezy/sys 2>&-
#  umount $DEB_BASE/env/wheezy/proc 2>&-
#  umount $DEB_BASE/env/wheezy/dev/pts 2>&-
#  umount $DEB_BASE/env/wheezy/dev 2>&-
  fi

  umount $ENV_BASE 2> /dev/null

następnie w Debianie:
edytując /etc/init.d/rtorrent
Bash:
d_start() {
  chmod 666 /dev/ptmx ; chmod 666 /dev/null
  chmod 666 /wheezy/dev/ptmx ; chmod 666 /wheezy//dev/null

  echo "
  [rtorrent] Mounting shares"
  mount -o bind /share/Download /wheezy/share/Download
  mount -o bind /share/Multimedia /wheezy/share/Multimedia
  mount -o bind /share/Public /wheezy/share/Public
  mount -o bind /share/Usb /wheezy/share/Usb
  mount -o bind /var/www /wheezy/var/www
  mount -o bind /tmp /wheezy/tmp

dopisujemy zaraz za mount -o bind /tmp /wheezy/tmp
Bash:
  [ ! -d "/wheezy/tmp.qnap" ] && mkdir -p /wheezy/tmp.qnap
  mount -o rbind /tmp.qnap /wheezy/tmp.qnap

następnie odnajdujemy
Bash:
d_stop() {
  session=`getsession "$config"`
  if ! [ -s /wheezy/${session}/rtorrent.lock ] ; then
  return
  fi
  pid=`cat /wheezy/${session}/rtorrent.lock | awk -F: '{print($2)}' | sed "s/[^0-9]//g"`
  if ps -A | grep -sq ${pid}.*rtorrent ; then # make sure the pid doesn't belong to another process
  kill -s INT ${pid}

  x=8;
  while [ ! -z "`ps | grep rtorrent | grep ${pid}`" -a "$x" -gt 0 ]; do
  echo "[rtorrent] --SIGINT  ... $x seconds left"
  x=$(expr $x - 1)
  ${BINDIR}/sleep 1
  done

  if ps -A | grep -sq ${pid}.*rtorrent ; then
  kill -s TERM ${pid}
  x=5;
  while [ ! -z "`ps | grep rtorrent | grep ${pid}`" -a "$x" -gt 0 ]; do
  echo "[rtorrent] --SIGTERM  ... $x seconds left"
  x=$(expr $x - 1)
  ${BINDIR}/sleep 1
  done
  fi

  if ps -A | grep -sq ${pid}.*rtorrent ; then
  kill -s KILL ${pid}
  echo "[rtorrent] --SIGKILL  ... 0 seconds left"
  fi
  fi

  sleep 1
  sync
  sleep 1
  echo "
  [rtorrent] Umounting shares"
  umount /wheezy/share/Download
  umount /wheezy/share/Multimedia
  umount /wheezy/share/Public
  umount /wheezy/share/Usb
  umount /wheezy/var/www
  umount /wheezy/tmp

i dopisujemy za umount /wheezy/tmp

Bash:
umount /wheezy/tmp.qnap

W ten sposób widzimy zawartość katalogu /tmp z QTS jako /wheezy/tmp.qnap. Pozwala nam to komunikację z LogManem.
Po restarcie NAS Debian powinien widzieć już nowy katalog.

Następnie w Debianie trzeba dopisać dwie rzeczy:
1. edytować/stworzyć plik /share/Download/rtorrent/settings/settings/notify_svc.sh
Bash:
ARGS=75
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]
then
  echo "rtorrent-QNAP Announcement Tool (c)2009-2014 Silas Mariusz"
  echo "Usage: ./`basename $0` <service> <action> <message>"
  echo
  exit $E_NOARGS
fi
n_svc=$1
n_action=$2
shift 2
n_message=$@
# Theme
case $n_action in
  "FINISH")
  if [ "$n_svc" == "event_log" ]; then
  t_action="Download finished:"
  elif [ "$n_svc" == "smsc" ]; then
  t_action="Complete:"
  else
  t_action="Finished:"
  fi
  ;;
  "INSERT")
  if [ "$n_svc" == "event_log" ]; then
  t_action="New download:"
  elif [ "$n_svc" == "smsc" ]; then
  t_action="Start :"
  else
  t_action="Inserted:"
  fi
  ;;
  *)
  t_action="($0: line:$LINENO error) $n_svc"
  ;;
esac
case $n_svc in
  "smsc")

  _sms_log="/share/Download/rtorrent/logs/sms.out"
  echo "rTorrent $t_action $n_message" >> $_sms_log
#  [ -x "/usr/sbin/sms_sender" ] && /usr/sbin/sms_sender -m "$t_action $n_message"
  ;;
  "event_log")
  __now_date=$(date +%Y-%m-%d)
  __now_time=$(date +%H:%M:%S)
  __hostname=$(hostname)
  _tail_log="/share/Download/rtorrent/logs/announce.out"

  echo -e "Rtorrent Events: \n$__now_date · $__now_time —— [b]rtorrent[/b]×[i]$__hostname[/i] —— [u]EVENT:[/u] [b]$t_action[/b] $n_message\n" >> $_tail_log
  ;;
  *)
  echo "(error) Unsupported notify service"
  echo
  exit 1
  ;;
esac
kill -HUP $(cat /tmp.qnap/logman-worker.pid)
exit 0
Dla świętego spokoju polecam poprawić mu prawa dostępu
Bash:
chmod 777 /share/Download/rtorrent/settings/settings/notify_svc.sh

2. Dopisać linie informującą rtorrenta do wykonania extra akcji przy dodaniu i zakończeniu pobierania
/wheezy/etc/rtorrent.conf
Bash:
# When the torrent finishes, it executes "mv -n <base_path> ~/Download/"
# and then sets the destination directory to "~/Download/". (0.7.7+)
#on_finished = move_complete,"execute=mv,-u,$d.get_base_path=,/share/Download/rtorrent/complete/ ;d.set_directory=/share/Download/rtorrent/complete/"
method.set_key = event.download.finished,move_complete,"d.set_directory=/share/Download/rtorrent/complete/; execute=mv,-f,$d.get_base_path=,/share/Download/rtorrent/complete/"
###

dopisać po ###

Bash:
method.set_key = event.download.finished,notify_event_log_finished,"execute=/share/Download/rtorrent/settings/settings/notify_svc.sh,event_log,FINISH,$d.get_name="
method.set_key = event.download.inserted_new,notify_event_log_inserted_new,"execute=/share/Download/rtorrent/settings/settings/notify_svc.sh,event_log,INSERT,$d.get_name="
method.set_key = event.download.finished,notify_smsc_finished,"execute=/share/Download/rtorrent/settings/settings/notify_svc.sh,smsc,FINISH,$d.get_name="
method.set_key = event.download.inserted_new,notify_smsc_inserted_new,"execute=/share/Download/rtorrent/settings/settings/notify_svc.sh,smsc,INSERT,$d.get_name="
###

Popisaliśmy trochę - to sprawdźmy efekty naszych działań:
w Debianie wydajmy polecenie
Bash:
/share/Download/rtorrent/settings/settings/notify_svc.sh smsc INSERT test sms
oraz
Bash:
/share/Download/rtorrent/settings/settings/notify_svc.sh event_log INSERT test gg
Po około minucie powinien przyjść SMS z treścią " test sms" a na GG (jeśli sobie ustawiliście w Logmanie) "test gg"

Upload 2014 12 15 18 42 15


PS: @Silas Mariusz - merguj ten kod - bo ja tutorial dodałem ;)
 
  • Lubię to
Reakcje: Paweł Tołoczko
Skrypty dla innych urządzeń, gotowe do pracy z botem Logman


Mikrotik RouterBoard OS - Monitorowanie przyłączonych klientów do sieci bezprzewodowej

(Script) Skrypt:
Nazwa: log_client
Reguły uruchamiania: wszystkie opcje
Kod:
# BEGIN SETUP
#:local systemName [/system identity get name]
:local systemName [:system identity get value-name=name]
# END SETUP

# Podaj docelowy numer Gadu Gadu
:local gadugadu "1234567"
:local rawOutput
:local output

:foreach i in=[ /int wir reg find ap=no] do={
	:set rawOutput ("AP: " . [int wir reg get $i interface] . "  MAC: " . [int wir reg get $i mac-address ] . " Last IP:" . [int wir reg get $i last-ip] . " RX: " . [int wir reg get $i rx-rate] . " TX: " . [int wir reg get $i tx-rate] . " Uptime: " . [int wir reg get $i uptime] . " LastACT: " . [int wir reg get $i last-activity] . " SignalStrength: " . [int wir reg get $i signal-strength] . " SNR: " . [int wir reg get $i signal-to-noise] . " TX/RX-CCQ: " . [int wir reg get $i tx-ccq] . " / " . [int wir reg get $i rx-ccq] . " PThroughput: " . [int wir reg get $i  p-throughput])

	:set output ("Mikrotik [b]" . [/system identity get name] . "[/b] [u]AP[/u]: [i]" . [int wir reg get $i interface] . "[/i]  MAC: [u]" . [int wir reg get $i mac-address ] . "[/u] Last IP:[b]" . [int wir reg get $i last-ip] . "[/b] RX: [b]" . [int wir reg get $i rx-rate] . "[/b] TX: [b]" . [int wir reg get $i tx-rate] . "[/b] Uptime: [u]" . [int wir reg get $i uptime] . "[/u] LastACT: " . [int wir reg get $i last-activity] . " SignalStrength: " . [int wir reg get $i signal-strength] . " SNR: [u]" . [int wir reg get $i signal-to-noise] . "[/u] TX/RX-CCQ: [u]" . [int wir reg get $i tx-ccq] . "[/u] / [u]" . [int wir reg get $i rx-ccq] . "[/u] PThroughput: " . [int wir reg get $i  p-throughput])

	if ([:len $output] > 0) do={
	  :local urlstring "http://pool.qnapclub.pl/projects/tools/bot-log-gadugadu/bot.php\?number=$gadugadu&message=$output"
	  :local urlEncoded

	  :for i from=0 to=([:len $urlstring] - 1) do={ 
		:local char [:pick $urlstring $i]
		:if ($char = " ") do={
		  :set $char "%20"
		}
		:if ($char = "-") do={
		  :set $char "%2D"
		}
		:if ($char = "+") do={
		  :set $char "%2B"
		}
		:set urlEncoded ($urlEncoded . $char)
	  }

	  :log info ($rawOutput)
	  #:beep frequency=90 length=500ms
	  /tool fetch url="$urlEncoded" mode=http keep-result=no
	}

}
(Scheduler) Harmonogram
Nazwa nowego zadania: log_client
Czas rozpoczęcia: startup
Interwał: 00:05:00
Przy wystąpieniu zdarzenia wykonaj (On Event):
log_client
Reguły uruchamiania: wszystkie



Mikrotik RouterBoard OS - Powiadom o przyznaniu adresu IP przez serwer DHCP oraz alarmuj na wypadek udanych i nieudanych prób logowania do routera

(Script) Skrypt:
Nazwa: Logman
Reguły uruchamiania: wszystkie opcje
Kod:
# BEGIN SETUP
:local scheduleName "Logman"
#:local systemName [/system identity get name]
:local systemName [:system identity get value-name=name]
:local startBuf [:toarray [/log find message~"logged in" || message~"login failure" || message~"assigned"]]
:local removeThese {"telnet";"whatever string you want"}
# END SETUP

# Podaj docelowy numer Gadu Gadu
:local gadugadu "7662900"

# warn if schedule does not exist
:if ([:len [/system scheduler find name="$scheduleName"]] = 0) do={
  /log warning "[Logman] ERROR: Schedule does not exist. Create schedule and edit script to match name"
}

# get last time
:local lastTime [/system scheduler get [find name="$scheduleName"] comment]
# for checking time of each log entry
:local currentTime
# log message
:local message

# final output
:local output

:local keepOutput false
# if lastTime is empty, set keepOutput to true
:if ([:len $lastTime] = 0) do={
  :set keepOutput true
}

:local counter 0
# loop through all log entries that have been found
:foreach i in=$startBuf do={

# loop through all removeThese array items
  :local keepLog true
  :foreach j in=$removeThese do={
#   if this log entry contains any of them, it will be ignored
    :if ([/log get $i message] ~ "$j") do={
      :set keepLog false
    }
  }
  :if ($keepLog = true) do={
   
   :set message [/log get $i message]

#   LOG DATE
#   depending on log date/time, the format may be different. 3 known formats
#   format of jan/01/2002 00:00:00 which shows up at unknown date/time. Using as default
    :set currentTime [ /log get $i time ]
#   format of 00:00:00 which shows up on current day's logs
   :if ([:len $currentTime] = 8 ) do={
     :set currentTime ([:pick [/system clock get date] 0 11]." ".$currentTime)
    } else={
#     format of jan/01 00:00:00 which shows up on previous day's logs
     :if ([:len $currentTime] = 15 ) do={
        :set currentTime ([:pick $currentTime 0 6]."/".[:pick [/system clock get date] 7 11]." ".[:pick $currentTime 7 15])
      }
   }
   
#   if keepOutput is true, add this log entry to output
   :if ($keepOutput = true) do={
     :set output ($output."[i]".$currentTime."[/i] ".$message."[br]")
   }
#   if currentTime = lastTime, set keepOutput so any further logs found will be added to output
#   reset output in the case we have multiple identical date/time entries in a row as the last matching logs
#   otherwise, it would stop at the first found matching log, thus all following logs would be output
    :if ($currentTime = $lastTime) do={
     :set keepOutput true
     :set output ""
   }
  }

#   if this is last log entry
  :if ($counter = ([:len $startBuf]-1)) do={
#   If keepOutput is still false after loop, this means lastTime has a value, but a matching currentTime was never found.
#   This can happen if 1) The router was rebooted and matching logs stored in memory were wiped, or 2) An item is added
#   to the removeThese array that then ignores the last log that determined the lastTime variable.
#   This resets the comment to nothing. The next run will be like the first time, and you will get all matching logs
   :if ($keepOutput = false) do={
#     if previous log was found, this will be our new lastTime entry      
     :if ([:len $message] > 0) do={
        :set output ($output."[i]".$currentTime."[/i] ".$message."[br]")
      }
    }
  }
  :set counter ($counter + 1)
}

# If we have output, save new date/time, and send email
if ([:len $output] > 0) do={
  /system scheduler set [find name="$scheduleName"] comment=$currentTime
  :local urlstring "http://pool.qnapclub.pl/projects/tools/bot-log-gadugadu/bot.php\?number=$gadugadu&message=$output"
  :local urlEncoded;

  :for i from=0 to=([:len $urlstring] - 1) do={ 
    :local char [:pick $urlstring $i]
    :if ($char = " ") do={
	  :set $char "%20"
    }
    :if ($char = "-") do={
	  :set $char "%2D"
    }
    :if ($char = "+") do={
	  :set $char "%2B"
    }
    :set urlEncoded ($urlEncoded . $char)
  }

  /log info "[Logman] New logs found, send get/post"
  /tool fetch url="$urlEncoded" mode=http keep-result=no

  #:beep frequency=90 length=500ms
(Scheduler) Harmonogram
Nazwa nowego zadania: Logman
Czas rozpoczęcia: startup
Interwał: 00:00:30
Przy wystąpieniu zdarzenia wykonaj (On Event):
Logman
Reguły uruchamiania: wszystkie

Upload 2015 11 8 20 26 53



Mikrotik RouterBoard OS - Log Parser z obsługą zdarzeń (potrzebuje kilka poprawek...)

(Script) Skrypt:
Utwórz nową akcje logowania, aby zapisać poszczególne reguły informacji w niezależnym bufforze w pamięci RAM:
Kod:
/system logging action add memory-lines=100 memory-stop-on-full=no name=logParse target=memory
Przyznaj zezwolonia logowania poszczególnych zdarzeń dla utworzonego nowego buffora pamięci:
Kod:
/system logging add action=logParse disabled=no prefix="" topics=system,info
/system logging add action=logParse disabled=no prefix="" topics=system,error,critical
/system logging add action=logParse disabled=no prefix="" topics=dhcp
Nazwa: Log-Parser
Reguły uruchamiania: wszystkie opcje
Kod:
# Script Name: Log-Parser
# This script reads a specified log buffer.  At each log entry read,
# the global variable 'logParseVar' is set to "<log entry time>,<log entry topics>,<log entry message>"
# then a parser action script is run.  The parser action script reads the global variable, and performs specified actions.
# The log buffer is then cleared, so only new entries are read each time this script gets executed.

# Podaj docelowy numer Gadu Gadu
:local gadugadu "1234567"

# Set this to a "memory" action log buffer
:local logBuffer "logParse"

# Set to name of parser script to run against each log entry in buffer
:local logParserScript "Log-Parser-Script"

# Internal processing below....
# -----------------------------------
:global logParseVar ""

:local loglastparsetime
:local loglastparsemessage
:local findindex
:local property
:local value
:local logEntryTopics
:local logEntryTime
:local logEntryMessage
:local curDate
:local curMonth
:local curDay
:local curYear
:local clearedbuf
:local lines

# Get current date settings
:set curDate [/system clock get date]
:set curMonth [:pick [:tostr $curDate] 0 3]
:set curDay [:pick [:tostr $curDate] 4 6]
:set curYear [:pick [:tostr $curDate] 7 11]

:set clearedbuf 0
:foreach rule in=[/log print where buffer=logParse] do={
# Now all data is collected in memory..
#:foreach rule in=$logBuffer do={
#:foreach rule in=[/log print where buffer=($logBuffer)] do={
#:foreach rule in=[/log print where buffer="$logBuffer"] do={
# Now all data is collected in memory..

# Clear log buffer right away so new entries come in
   :if ($clearedbuf = 0) do={
      /system logging action {
         :set lines [get ($logBuffer) memory-lines]
         set ($logBuffer) memory-lines 1
         set ($logBuffer) memory-lines $lines
      }
      :set clearedbuf 1
   }
# End clear log buffer

   :set logEntryTime ""
   :set logEntryTopics ""
   :set logEntryMessage ""

# Get each log entry's properties
   :local items {$rule}
   :foreach item in=[$items] do={
      :set logEntryTime ($item->"time")
      :set logEntryTopics ($item->"topics")
      :set logEntryMessage ($item->"message")
   }
# end foreach item
   }

# Set logEntryTime to full time format (mmm/dd/yyyy HH:MM:SS)
   :set findindex [:find [:tostr $logEntryTime] " "]
# If no spaces are found, only time is given (HH:MM:SS), insert mmm/dd/yyyy
   :if ([:len $findindex] = 0) do={
      :set logEntryTime ($curMonth . "/" . $curDay . "/" . $curYear . " " . \
                                    [:tostr $logEntryTime])
   }
# Only (mmm/dd HH:MM:SS) is given, insert year
   :if ($findindex = 6) do={
      :set logEntryTime ([:pick [:tostr $logEntryTime] 0 $findindex] . "/" . $curYear . \
                                    [:pick [:tostr $logEntryTime] $findindex [:len [:tostr $logEntryTime]]])
   }
# Only (mmm HH:MM:SS) is given, insert day and year
   :if ($findindex = 3) do={
      :set logEntryTime ([:pick [:tostr $logEntryTime] 0 $findindex] . "/" . $curDay . "/" . $curYear . \
                                    [:pick [:tostr $logEntryTime] $findindex [:len [:tostr $logEntryTime]]])
   }
# End set logEntryTime to full time format

# Skip if logEntryTime and logEntryMessage are the same as previous parsed log entry
   :if ($logEntryTime = $loglastparsetime && $logEntryMessage = $loglastparsemessage) do={
   } else={
#   Set logParseVar, then run parser script
      :set logParseVar {$logEntryTime ; $logEntryTopics; $logEntryMessage}


      :local urlstring "http://pool.qnapclub.pl/projects/tools/bot-log-gadugadu/bot.php\?number=$gadugadu&message=$logEntryMessage"
      :local urlEncoded;

      :for i from=0 to=([:len $urlstring] - 1) do={ 
        :local char [:pick $urlstring $i]
        :if ($char = " ") do={
    	  :set $char "%20"
        }
        :if ($char = "-") do={
    	  :set $char "%2D"
        }
        :if ($char = "+") do={
    	  :set $char "%2B"
        }
        :set urlEncoded ($urlEncoded . $char)
      }

      # UNCOMMENT TO GET DETAILED VERBOSE OUTPUIT
      #:put "$logParseVar"
      /tool fetch url="$urlEncoded" mode=http keep-result=no

      /system script run ($logParserScript)

#   Update last parsed time, and last parsed message
      :set loglastparsetime $logEntryTime
      :set loglastparsemessage $logEntryMessage
   }

# end foreach rule
}
(Script) Skrypt 2:
Nazwa: Log-Parser-Script
Reguły uruchamiania: wszystkie opcje
Kod:
# Script Name: Log-Parser-Script
#
# This is an EXAMPLE script.  Modify it to your requirements.
#
# This script will work with all v3.x and v4.x
# If your version >= v3.23, you can use the ~ operator to match against
# regular expressions.

# Podaj docelowy numer Gadu Gadu
:local gadugadu "1234567"

# Get log entry data from global variable and store it locally
:global logParseVar
:local logTime ($logParseVar->0)
:local logTopics [:tostr ($logParseVar->1)]
:local logMessage [:tostr ($logParseVar->2)]
:set logParseVar ""

:local ruleop
:local loguser
:local logsettings
:local findindex
:local tmpstring

# Uncomment to view the log entry's details
:put ("Log Time: " . $logTime)
:put ("Log Topics: " . $logTopics)
:put ("Log Message: " . $logMessage)

# Check for login failure
:if ([:find [:tostr $logMessage] "login failure"] != "") do={
#   :beep frequency=90 length=500ms
#   :beep frequency=130 length=500ms
   :put ("A login failure has occured.  Take some action")
}
# End check for login failure

# Check for logged in users
:if ([:find [:tostr $logMessage] "logged in"] != "") do={
#   :beep frequency=900 length=300ms
#   :beep frequency=1300 length=200ms
   :put ("A user has logged in.")
}
# End check for logged in users

# Check for configuration changes: added, changed, or removed
:if ([:tostr $logTopics] = "system;info") do={
   :set ruleop ""
   :if ([:len [:find [:tostr $logMessage] "changed "]] > 0) do={ :set ruleop "changed" }
   :if ([:len [:find [:tostr $logMessage] "added "]] > 0) do={ :set ruleop "added" }
   :if ([:len [:find [:tostr $logMessage] "removed "]] > 0) do={ :set ruleop "removed" }

   :if ([:len $ruleop] > 0) do={
      :set tmpstring $logMessage
      :set findindex [:find [:tostr $tmpstring] [:tostr $ruleop]]
      :set tmpstring ([:pick [:tostr $tmpstring] 0 $findindex] . \
                               [:pick [:tostr $tmpstring] ($findindex + [:len [:tostr $ruleop]]) [:len [:tostr $tmpstring]]])
      :set findindex [:find [:tostr $tmpstring] " by "]
      :set loguser ([:pick [:tostr $tmpstring] ($findindex + 4) [:len [:tostr $tmpstring]]])
      :set logsettings [:pick [:tostr $tmpstring] 0 $findindex]

      :put ($loguser . " " . $ruleop . " " . $logsettings . " configuration.  We should take a backup now.")
   }
}
# End check for configuration changes

# Check for DHCP lease assigned/deassigned
:if ([:tostr $logTopics] = "dhcp;info") do={
   :set ruleop ""
   :if ([:len [:find [:tostr $logMessage] "assigned "]] > 0) do={ :set ruleop "assigned" }
   :if ([:len [:find [:tostr $logMessage] "deassigned "]] > 0) do={ :set ruleop "deassigned" }

   :if ([:len $ruleop] > 0) do={
      :if ($ruleop = "assigned") do={
         :put ("A new dhcp lease has been assigned.  Check the DHCP IP Pool addresses")
      }
      :if ($ruleop = "deassigned") do={
         :put ("A dhcp lease has been removed.  Remove the host-name from static DNS")
      }
   }
}
# End check for new DHCP lease assigned
(Scheduler) Harmonogram
Nazwa nowego zadania: Log-Parser
Czas rozpoczęcia: startup
Interwał: 00:00:30
Przy wystąpieniu zdarzenia wykonaj (On Event):
Log-Parser
Reguły uruchamiania: wszystkie
 
  • Lubię to
Reakcje: kaktus
Mikrotik RouterBoard OS - Skrypt konwertujący nazwy klientów DHCP do statycznych adresów DNS oraz informujący o tej czynności za pośrednictwem Logmana

Static DNS from DHCP clients


Upload 2016 2 28 13 22 23


(Script) Skrypt:
Nazwa: Static-DNS-from-DHCP-clients
Reguły uruchamiania: wszystkie opcje
Kod:
# Creates static DNS entres for DHCP clients in the named DHCP server.
# Hostnames passed to DHCP are appended with the zone.

# Set the first two variables according to your installation.
:local dhcpserver "dhcp-local"
:local zone "local.devSpark.pl"

# Numer Gadu-Gadu
:local gadugadu "1234567890"

# Set the TTL to the scheduler frequency for this script.
:local ttl "00:05:00"

:local curTime
:local curDate
:local currentDateTime
:local identifyname
:set curDate [/system clock get time]
:set curDate [/system clock get date]
:set currentDateTime ($curDate." ".$curTime)
:set identifyname [/system identity get name]

:local message
:local output

# Clear old static DNS entries matching the zone and TTL.
/ip dns static
:foreach dnsrecord in=[find where name ~ (".*\\.".$zone) ] do={
	:local fqdn [ get $dnsrecord name ]
	:local hostname2 [ :pick $fqdn 0 ( [ :len $fqdn ] - ( [ :len $zone ] + 1 ) ) ]
	:local hostname

	:if ( [ :len $hostname2 ] > 0) do={
		:for i from=0 to=([:len $hostname2] - 1) do={
			:local char [:pick $hostname2 $i]
			:if ($char = "\00") do={
				:set $char ""
			}
			:if ($char = " ") do={
				:set $char "-"
			}
			:if ($char = "-") do={
				:set $char "-"
			}
			:if ($char = "+") do={
				:set $char "-"
			}
			:set hostname ($hostname . $char)
		}
	}

	:local recordttl [get $dnsrecord ttl]
	:if ( $recordttl != $ttl ) do={
		:log debug ("Ignoring DNS record $fqdn with TTL $recordttl")
	} else={
		/ip dhcp-server lease
		:local dhcplease [ find where host-name ~ ($hostname.".*") and server="$dhcpserver"]
		:if ( [ :len $dhcplease ] > 0) do={
			:log debug ("DHCP lease exists for $hostname in $dhcpserver, keeping DNS record $fqdn")
		} else={
			:log info ("DHCP lease expired for $hostname, deleting DNS record $fqdn")
			:set output ($output."DHCP lease [i]expired[/i] for [b]".$hostname."[/b] [u]deleting[/u] DNS record [b]".$fqdn."[/b][br]")
			/ip dns static remove $dnsrecord
		}
	}
}

# Create or update static DNS entries from DHCP server leases.
/ip dhcp-server lease
:foreach dhcplease in=[find where server ~ ("$dhcpserver")] do={
	:local hostname2 [ get $dhcplease host-name ]

	:if ( [ :len $hostname2 ] > 0) do={

		:local hostname
		:for i from=0 to=([:len $hostname2] - 1) do={
			:local char [:pick $hostname2 $i]
			:if ($char = "\00") do={
				:set $char ""
			}
			:if ($char = " ") do={
				:set $char "-"
			}
			:if ($char = "-") do={
				:set $char "-"
			}
			:if ($char = "+") do={
				:set $char "-"
			}
			:set hostname ($hostname . $char)
		}

		:local dhcpip [ get $dhcplease address ]
		:local fqdn ( $hostname . "." . $zone )
		/ip dns static
		:local dnsrecord [ find where name=$fqdn ]
		:if ( [ :len $dnsrecord ] > 0 ) do={
			:local dnsip [ get $dnsrecord address ]
			:if ( $dnsip = $dhcpip ) do={
				:log debug ("DNS record for $fqdn to $dhcpip is up to date")
			} else={
				:log info ("Updating DNS record for $fqdn to $dhcpip")
				#:set output ($output."Updating DNS record for [b]".$fqdn."[/b] to ".$dhcpip."[br]")
				/ip dns static remove $dnsrecord
				/ip dns static add name=$fqdn address=$dhcpip ttl=$ttl
			}
		} else={
			:log info ("Creating DNS record for $fqdn to $dhcpip")
			:set output ($output."[b]Creating[/b] DNS record for [b]".$fqdn."[/b] to [u]".$dhcpip."[/u][br]")
			/ip dns static add name=$fqdn address=$dhcpip ttl=$ttl
		}
	}
}




:if ( [ :len $output ] > 0 ) do={
:set output ("Mikrotik [b]".$identifyname."[/b]: Static-DNS-from-DHCP-clients[br]".$output."[br]")
:local urlstring "http://pool.qnapclub.pl/projects/tools/bot-log-gadugadu/bot.php\?number=$gadugadu&message=$output"
:local urlEncoded
	  :for i from=0 to=([:len $urlstring] - 1) do={
		:local char [:pick $urlstring $i]
		:if ($char = " ") do={
		  :set $char "%20"
		}
		:if ($char = "-") do={
		  :set $char "%2D"
		}
		:if ($char = "+") do={
		  :set $char "%2B"
		}
		:set urlEncoded ($urlEncoded . $char)
	  }
	  /tool fetch url="$urlEncoded" mode=http keep-result=no
}

#:beep frequency=90 length=500ms

(Scheduler) Harmonogram
Nazwa nowego zadania: Static-DNS-from-DHCP-clients
Czas rozpoczęcia: startup
Interwał: 00:05:00
Przy wystąpieniu zdarzenia wykonaj (On Event):
Static-DNS-from-DHCP-clients
Reguły uruchamiania: wszystkie
 
Update ChangeLog 0.94
Dodana możliwość ignorowania logów zawierających treść oraz od określonych użytkowników.

Ignorowanie logów od określonych użytkowników lub zawierających treść

Aby ignorować wiadomości log zawierające określoną treść lub pochodzące od określonego użytkownika w katalogu, w którym zainstalowany jest logman umieść odpowiednio pliki:
  • ignore.lst - zawierający ignorowane słowa (w każdej linii osobno)
  • ignore.usr - zawierający ignorowanych użytkowników (w każdej linii osobno)

np.
ignore.lst napisał:
Public/Music
Music/
Pool/Movies
ignore.usr napisał:
 
ciekawe ...

Upload 2018 2 16 16 45 42


a dodałem ignora na jeden katalog w formie słowa /anime/ czy też ANIME/ ANIME

myślę że coś musisz dopisać nam tutaj :p

czy to jest udział/podkatalog bez / na końcu początku ?
 
teraz zero logów na gg ...
Bash:
[/share/CACHEDEV1_DATA/.qpkg/logman] # cat ignore.usr
[/share/CACHEDEV1_DATA/.qpkg/logman] # cat ignore.lst
DATA2/Marek
[/share/CACHEDEV1_DATA/.qpkg/logman] #

Upload 2018 2 16 20 44 19
 
ignore nie może być pusty:

do ignore.usr daj:
Kod:
# AVOID! DO NOT REMOVE THIS COMMENT TAG
# ------------------------------------------------------------------------------
# Type bellow user names line by line which you wanna ignore in log notification
osmc

a do ingore.lst:
Kod:
# AVOID! DO NOT REMOVE THIS COMMENT TAG
# -----------------------------------------------------------------------------------------------------------
# Type bellow ignored containing strings line by line which you wanna ignore in log connections notifications
 

Mogą Cię zainteresować

Użytkownicy znaleźli tą stronę używając tych słów:

  1. logman
  2. zabbix
  3. wprowadzanie poświadczeń