Shell-Script
根據日誌文件中的特定搜尋發送自定義內容
使用 below
test.sh
,我得到dump.txt
如下結果:test.sh:
#!/bin/bash #"Maxl-script" zone starts..... essmsh -l admin password -s localhost -i << EOF spool on to 'dump.txt'; display session all; spool off; EOF #"Maxl-script" zone ends.....
轉儲.txt:
user session login_time application database db_connect_time request request_time connection_source connection_ip request_state +-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+-------------------+------------------- admin 0 9 0 none 0 Not Requested* a00:bf32:: admin 989855740 1335 DRRDEVMH DRRPRODB 1201 none 0 Not Requested a00:8a45:: admin 1768947706 932 test test 916 none 0 Not Requested a00:94b6:: WARNING - 1241024 - Possible string truncation in column 1. WARNING - 1241028 - Output column defined with warnings. WARNING - 1241024 - Possible string truncation in column 9. WARNING - 1241028 - Output column defined with warnings. WARNING - 1241024 - Possible string truncation in column 10. WARNING - 1241028 - Output column defined with warnings. OK/INFO - 1241044 - Records returned: [3].
正如我們在最後一行看到的,
dump.txt
有一個字元串Records returned: [3]
。該數字 3 是我的目標,我想向具有以下行作為電子郵件正文的使用者發送電子郵件通知:Total Number of Sessions running = 3 NOTE: This is an automatically generated email, please don't reply to it.
Google搜尋後,我設法得到以下方法來完成它。
任何人都可以幫助我了解如何使用
sed
或任何其他方法來滿足我在上述腳本中的目標嗎?$ var=Records returned : echo "Total Number of Sessions running = $var | sed 's/.*://' " > file.tmp echo -e "\n" >> file.tmp echo "NOTE: This is an automatically generated email, please don't reply to it." >> file.tmp fi mailx -s "Subject" emailaddresses < file.tmp rm file.tmp
注意:
Records Returned...
行將始終是dump.txt中的最後一行。
您還可以使用
grep
和積極的前瞻:$ grep -oP '(\d+)(?=\].s*$)' dump.txt 3
上面的正則表達式搜尋最長的數字字元串,後跟
].
0 個或多個空格,直到行尾。您可以將其與電子郵件的其餘部分結合起來,如下所示:$ read -r -d '' message <<'EOF' > Total Number of Sessions running = $(grep -oP '(\d+)(?=\].\s*$)' dump.txt) > > NOTE: This is an automatically generated email, please don't reply to it. > EOF $ echo "$message" | mailx -s "Subject" emailaddresses
要做到這一點,請鍵入
read -r -d '' message <<'EOF'
並點擊Enter
。然後,再次粘貼或鍵入Total Number of Sessions running = $(grep -oP '(\d+)(?=\].\s*$)' dump.txt)
hitEnter
(任意多次),粘貼其餘的消息並寫入 EOF 以退出。