Часто бывает, что кто-то просит найти письмо такого-то пользователя, которое было отправлено позавчера, например. Можно перерывать логи руками, а можно воспользоваться скриптом, который любезно прислал один из читателей:
#!/bin/sh
to_grep="$*"
if [ ${#to_grep} = 0 ]
then
echo "
STOP: Where is search string?
" > /dev/stderr
exit 1
fi
tmp_major_filename="/tmp/searchmajortmp$$"
rm -f "${tmp_major_filename}"
# Мониторим Ctrl+C чтобы не оставлять хвостов из временных файлов.
trap 'rm -f ${tmp_major_filename} ;echo ; exit 13' TERM INT
exlog_log="/var/log/exim/mainlog"
if [ ! -r "${exlog_log}" ]
then
echo "
STOP: Where is exim log?
" > /dev/stderr
exit 1
fi
today_is=`date +%Y-%m-%d`
echo "1" | awk -v today_is="${today_is}" -v rex_log="${exlog_log}" '{
dl_cn = 0 # устанавливаем счетчик дней в 0
# Получаем список файлов лога exim-a, считаем их количество.
cmd_get_file_list=("ls "rex_log"*")
while ((cmd_get_file_list |getline)> 0) {
++fl_cn
}
close (cmd_get_file_list)
# Узнаем что у нас за ОС
cmd_what_os=("uname -s")
cmd_what_os |getline os_is
close(cmd_what_os)
while (dl_cn < fl_cn) {
# Получаем три значения в массиве (год, месяц, день) - текущая дата.
if (dl_cn == 0) {
split(today_is,TEMPTODAY,"-")
today_is_month = TEMPTODAY[2]
month_arg = TEMPTODAY[2]
} else {
cmd_month_arg = (today_is_month - month_arg)
# Получаем три значения в массиве (год, месяц, день) - последнее число нужного нам предыдущего месяца.
if (os_is == "FreeBSD" || os_is == "Darwin") {
cmd_date_last_month=("date -v-"cmd_day_arg"d -v-"cmd_month_arg"m +%Y-%m-%d")
} else {
cmd_date_last_month=("date -d \""cmd_day_arg" days ago "cmd_month_arg" months ago\" +%Y-%m-%d")
}
cmd_date_last_month |getline
split($0,TEMPTODAY,"-")
close (cmd_date_last_month)
}
# Выясняем до какого числа месяца будем делать декремент.
days_until = (fl_cn - dl_cn)
if (days_until > 0) {
day_until = 1
} else {
day_until = days_until
}
cmd_day_arg = TEMPTODAY[3]
# Получаем список дат в нисходящем порядке, забиваем в массив.
for (tmp_td=TEMPTODAY[3];tmp_td>=day_until;tmp_td--) {
# Заодно пририсовываем нули для красоты.
if (length(tmp_td) == 1) {
day_number = ("0"tmp_td)
} else {
day_number = tmp_td
}
FILESLIST[++dl_cn] = (TEMPTODAY[1]"-"TEMPTODAY[2]"-"day_number)
}
# Проверяем первая ли у нас итерация цикла.
if (month_arg != today_is_month) {
month_arg--
}
split("",TEMPTODAY)
}
# Печать массива.
printf "\n"
for (xs=1;xs<=fl_cn;xs++) {
printf "\t%s%s%s\t%s\n" , "(", xs, ")", FILESLIST[xs]
}
split("",FILESLIST)
printf "\n\t"
exit
}'
read -p "Enter Digit: " num_to_grep
if [ ${#num_to_grep} = 0 ]
then
echo "
STOP: Where is digit?
" > /dev/stderr
exit 1
fi
awk -v tmfname="${tmp_major_filename}" -v today_is="${today_is}" -v num_to_grep="${num_to_grep}" -v rex_log="${exlog_log}" -v to_grep="${to_grep}" '{
# Проверяем пользовательский ввод. Устанавливаем переменную w_show.
if ($0 ~ /^[1-3]$/) {
w_show=$0
exit
} else {
printf "\n\t%s\n\n", msg_wrong_number > err_log
split("",QUEUEARR)
split("",REJARRAY)
was_error = 1
exit 1
}
} BEGIN {
q_cn = 0
r_cn = 0
err_log = "/dev/stderr"
# Сообщения
msg_nothing_to_show = "STOP: Nothing to show."
msg_no_records = "STOP: No Records."
msg_wrong_number = "STOP: Wrong number."
msg_header_major = "SUCCESS"
msg_header_minor = "FAILURE"
msg_header_summ = "SUMMARY"
# Паттерн очереди
patt_QUEbe = "^[A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9]-[A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9]-[A-Za-z0-9][A-Za-z0-9]$"
# Получаем список файлов лога exim-a, добавляем их в массив, считаем их количество.
cmd_get_file_list=("ls "rex_log"*")
while ((cmd_get_file_list |getline)> 0) {
FILESLIST[++fl_cn] = $0
}
close (cmd_get_file_list)
# Проверяем пользовательский ввод. Получаем имя файла, проверяем заархивирован ли он, устанавливаем необходимые переменные.
if (num_to_grep ~ /^[0-9]+$/ && (num_to_grep <= fl_cn && num_to_grep != 0)) {
ex_log = FILESLIST[num_to_grep]
tmpfilename_parts = split(FILESLIST[num_to_grep],TMPFILENAME,".")
if (TMPFILENAME[tmpfilename_parts] == "gz") {
first_grep = ("zgrep -ni \""to_grep"\" "ex_log)
second_grep = ("zgrep -f "tmfname" "ex_log)
pr_ex_log = ("zcat "ex_log)
} else {
first_grep = ("grep -ni \""to_grep"\" "ex_log)
second_grep = ("grep -f "tmfname" "ex_log)
pr_ex_log = ("cat "ex_log)
}
split("",TMPFILENAME)
split("",FILESLIST)
} else {
printf "\n\t%s\n\n", msg_wrong_number > err_log
was_error = 1
exit 1
}
# Запускаем греп лога екзима. Если в строке в нужном месте есть совпадение с паттерном очереди, и это не реджект,
# добавляем очередь в массив очередей. Иначе номер строки лога в массив номеров строк лога.
while ((first_grep |getline)> 0) {
if (split($0,TMPLINE,":")>0) {
testqueue = substr(TMPLINE[4],4,16)
if (testqueue ~ patt_QUEbe) {
if (substr(TMPLINE[4],21,8) == "rejected") {
REJARRAY[++r_cn] = TMPLINE[1]
} else if ((testqueue in QUEUEARR) == 0) {
QUEUEARR[testqueue]
++q_cn
}
} else {
REJARRAY[++r_cn] = TMPLINE[1]
}
}
split("",TMPLINE)
}
printf "\n"
close (first_grep)
# Считаем и печатаем сколько мы всего нашли. Заодно приглашение ввода номера того что хочется увидеть если чего-то нашли.
printf "\t%s\t%s\t%s\n", "(1)", msg_header_major, q_cn
printf "\t%s\t%s\t%s\n", "(2)", msg_header_minor, r_cn
printf "\t%s\t%s\t%s\n", "(3)", msg_header_summ, (q_cn+r_cn)
if ((q_cn+r_cn) == 0) {
printf "\n\t%s\n\n", msg_nothing_to_show > err_log
split("",QUEUEARR)
split("",REJARRAY)
was_error = 1
exit 1
} else {
printf "\n\t%s\t" , "Enter Digit:"
}
} END {
if (was_error == 1) {
exit 1
}
# Получаем значение год-месяц-день из лога который будем показывать.
pr_ex_log | getline
close (pr_ex_log)
actdte = substr($0,1,10)
# Устанавливаем переменные - элементы декора.
header_major = sprintf("%s%s%s%s%s", "-------------------------------- ",msg_header_major," ---------------------------------------- ",actdte," ----------------------")
header_minor = sprintf("%s%s%s%s%s", "-------------------------------- ",msg_header_minor," ---------------------------------------- ",actdte," ----------------------")
footer = sprintf("%s%s%s\n", "------------------------------------------------------------------------------- ",actdte," ----------------------")
splitter_completed = sprintf("%s", "+ ------------ c -- o -- m -- p -- l -- e -- t -- e -- d ---------------------- +")
cmd_more = "more"
# Пользователь возжелал увидеть очереди.
if (w_show == 1) {
if (q_cn == 0) {
split("",QUEUEARR)
split("",REJARRAY)
printf "\n\t%s\n\n", msg_no_records > err_log
exit 1
} else {
y = 1
z = 0
# Сбрасываем содержимое массива очередей во временный файл
for (tq in QUEUEARR) {
print (tq) >> tmfname
}
print(header_major)
# Грепаем лог екзима используя временный файл в качестве файла паттернов.
while ((second_grep |getline)> 0) {
if (length($0) == 46) {
if (substr($0,38,9) == "Completed") {
print (splitter_completed) | cmd_more
} else {
print(substr($0,12)) | cmd_more
}
} else {
print(substr($0,12)) | cmd_more
}
}
close (second_grep)
close (cmd_more)
print(footer)
}
# Пользователь возжелал увидеть отлупы.
} else if (w_show == 2) {
if (r_cn == 0) {
split("",QUEUEARR)
split("",REJARRAY)
printf "\n\t%s\n\n", msg_no_records > err_log
exit 1
} else {
y = 1
z = 0
print(header_minor)
while ((pr_ex_log |getline)> 0) {
z++
if(z == REJARRAY[y]){
print(substr($0,12)) | cmd_more
y++
}
}
close (pr_ex_log)
close (cmd_more)
print(footer)
}
# Пользователь возжелал увидеть все.
} else if (w_show == 3) {
if (r_cn != 0) {
y = 1
z = 0
print(header_minor)
while ((pr_ex_log |getline)> 0) {
z++
if(z == REJARRAY[y]){
print(substr($0,12)) | cmd_more
y++
}
}
close (pr_ex_log)
close (cmd_more)
print(footer)
}
if (q_cn != 0) {
y = 1
z = 0
# Сбрасываем содержимое массива очередей во временный файл
for (tq in QUEUEARR) {
print (tq) >> tmfname
}
print(header_major)
# Грепаем лог екзима используя временный файл в качестве файла паттернов.
while ((second_grep |getline)> 0) {
if (length($0) == 46) {
if (substr($0,38,9) == "Completed") {
print (splitter_completed) | cmd_more
} else {
print(substr($0,12)) | cmd_more
}
} else {
print(substr($0,12)) | cmd_more
}
}
close (second_grep)
close (cmd_more)
print(footer)
}
}
split("",QUEUEARR)
split("",REJARRAY)
}' -
rm -f "${tmp_major_filename}"
# Настройки логгирования в конфиге exim:
# --
# log_file_path = /var/log/exim/exim_%s.log
# write_rejectlog = no
#
# log_selector = \
# +all_parents \
# +connection_reject \
# -host_lookup_failed \
# -incoming_interface \
# -lost_incoming_connection \
# +received_sender \
# +received_recipients \
# +smtp_confirmation \
# +smtp_syntax_error \
# +smtp_protocol_error \
# -queue_run
#
# syslog_timestamp = yes
#
# --
#
# Ver 1.1
#
#1 by seo audit on 09.06.2020 - 15:09
Quote
There is certainly a lot to find out about this topic. I like all the points you’ve made. https://www.transtats.bts.gov/exit.asp?url=http://www.bsolutions5.com/website-design/ecommerce-development/
#2 by WilliamVot on 15.06.2020 - 21:54
Quote
Любителям пощекотать нервы определенно понравится квест призрак, невероятно атмосферное приключение.
#3 by enrishedarase on 18.10.2020 - 02:11
Quote
annual credit report completely free experian http://getcreditscoreww.com/# — free credit karma how to read credit report creditkarma
#4 by AmyRhype on 08.11.2020 - 21:05
Quote
paxil headache
#5 by https://ibiza-singles.com/ on 10.11.2020 - 06:20
Quote
https://westcoastyogafoundation.org/
#6 by Babalby on 15.11.2020 - 23:03
Quote
Нашла хорошего психолога batmanapollo.ru, который помогает достичь изменений.
#7 by Babalby on 15.11.2020 - 23:08
Quote
Умные не столько ищут одиночества, сколько избегают создаваемой дураками суеты. http://batmanapollo.ru
#8 by brerrerrudgeri on 16.11.2020 - 07:05
Quote
installment loans online direct lender http://quickcashkkel.com/# — loan online no credit check payday loans installment payday loans no credit check instant online payday loan
#9 by sfc-nargile on 03.12.2020 - 11:03
Quote
Hey there, I think your website might be having browser compatibility issues.
When I look at your website in Opera, it looks
fine but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up! Other then that, amazing blog!
#10 by zeyadetmanfitness on 03.12.2020 - 11:46
Quote
May I just say what a relief to uncover an individual who really understands what they are talking about
online. You definitely realize how to bring a problem to light and make it important.
More and more people need to look at this and understand this side of your story.
I was surprised that you are not more popular given that you most certainly possess the gift.
#11 by tanahunpost on 03.12.2020 - 13:07
Quote
With havin so much content do you ever run into any
issues of plagorism or copyright infringement? My website has
a lot of unique content I’ve either created myself or outsourced
but it looks like a lot of it is popping it up all
over the web without my agreement. Do you know any solutions to help
reduce content from being stolen? I’d really appreciate it.
#12 by datvanggiare on 04.12.2020 - 05:40
Quote
Can you tell us more about this? I’d like to find out more details.
#13 by saltlakecitywalkingtours on 05.12.2020 - 06:03
Quote
Hello it’s me, I am also visiting this web site daily, this
web site is actually nice and the people are truly
sharing nice thoughts.
#14 by parseads on 05.12.2020 - 07:49
Quote
I visit everyday some web sites and sites to read posts, however this website presents quality based
writing.
#15 by oorsanthai on 05.12.2020 - 08:33
Quote
Excellent post. I was checking constantly this blog and
I’m impressed! Very useful info specifically
the last part 🙂 I care for such information much.
I was looking for this particular info for a very long time.
Thank you and best of luck.
#16 by banhmitruyenthong on 06.12.2020 - 03:25
Quote
Wonderful beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog website?
The account helped me a acceptable deal. I had been tiny bit acquainted of
this your broadcast provided bright clear idea
#17 by hollyfair on 06.12.2020 - 10:14
Quote
Why viewers still use to read news papers when in this technological world all is accessible on net?
#18 by qdimart on 07.12.2020 - 05:56
Quote
Hi there to every one, the contents present at this website are
truly amazing for people experience, well, keep up the good
work fellows.
#19 by crazygirlcosmo on 07.12.2020 - 17:14
Quote
Thanks for a marvelous posting! I certainly enjoyed reading it, you’re a great author.
I will be sure to bookmark your blog and definitely will come back down the road.
I want to encourage one to continue your great posts, have a nice weekend!
#20 by geddespropiedades on 08.12.2020 - 05:13
Quote
Wonderful site you have here but I was curious if you knew of any message boards that cover the
same topics talked about in this article? I’d really like to be a part of community where I can get responses from other
knowledgeable people that share the same interest. If you have any suggestions, please let me know.
Thanks!
#21 by incomesourceout on 08.12.2020 - 16:34
Quote
Wonderful beat ! I would like to apprentice at
the same time as you amend your website, how could i subscribe for a weblog website?
The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast
provided bright transparent concept
#22 by matnemrooz on 08.12.2020 - 22:38
Quote
I do not even know the way I ended up here, but I assumed
this post was once great. I do not know who you are but definitely you’re going
to a well-known blogger when you are not already.
Cheers!
#23 by yxntravel on 09.12.2020 - 02:20
Quote
I do believe all the ideas you’ve introduced in your
post. They are very convincing and will certainly work.
Nonetheless, the posts are very quick for beginners.
May just you please lengthen them a little from next time?
Thank you for the post.
#24 by cartchacoulibaly on 09.12.2020 - 06:14
Quote
You actually make it appear so easy along with your presentation however I
to find this matter to be really one thing which I think I might never
understand. It seems too complicated and extremely wide for me.
I am looking forward on your subsequent post, I
will attempt to get the dangle of it!
#25 by buckshotpie on 09.12.2020 - 14:10
Quote
It’s truly very complicated in this full of activity life to listen news
on TV, therefore I just use world wide web for that
purpose, and get the most up-to-date information.
#26 by dinarareadymix on 11.12.2020 - 01:11
Quote
If some one wishes expert view concerning blogging and site-building afterward i advise him/her to go to see
this blog, Keep up the pleasant job.
#27 by company decor on 14.12.2020 - 07:38
Quote
Having read this I thought it was really enlightening.
I appreciate you spending some time and effort to put this article together.
I once again find myself personally spending a significant amount of time both reading and commenting. But so what, it was still worth it!
#28 by blog noi that on 19.12.2020 - 11:46
Quote
Loving the info on this web site, you have done great job onn the blog posts.Have a look at my page
#29 by thomas430.korefacilityservices.com on 26.12.2020 - 21:57
Quote
Valuable information. Lucky me I discovered your site accidentally, and I’m surprised
why this accident did not came about in advance! I bookmarked it.
#30 by bropay on 26.12.2020 - 21:57
Quote
generic cialis buy online buy generic cialis online generic cialis
#31 by mercurygroupinternational.com on 26.12.2020 - 22:16
Quote
I am really grateful to the owner of this site who has shared this
great article at at this place.
#32 by startupvessel.com on 28.12.2020 - 09:33
Quote
Very good blog you have here but I was curious about if
you knew of any user discussion forums that cover the same topics discussed
here? I’d really love to be a part of group where I can get feed-back from other experienced individuals that share the same interest.
If you have any recommendations, please let me know. Thank you!
#33 by challengertravels.com on 28.12.2020 - 11:10
Quote
If you want to obtain a great deal from this paragraph then you have to apply such techniques to your won web site.
#34 by mercurygroupinternational.com on 11.01.2021 - 14:15
Quote
Yes! Finally something about globalfinancemonetize.com.
#35 by minhthuyyoga.com on 14.01.2021 - 15:26
Quote
I do not even know the way I stopped up right here, but I
believed this submit was great. I do not realize who you’re but certainly you are going to a famous blogger if you aren’t already.
Cheers!
#36 by sajadghatei.com on 14.01.2021 - 15:44
Quote
What’s up, its good paragraph on the topic of media print,
we all be familiar with media is a enormous source of information.
#37 by saltkrafts.com on 15.01.2021 - 06:43
Quote
I’d like to thank you for the efforts you’ve put in penning this website.
I’m hoping to view the same high-grade blog posts by you in the future
as well. In truth, your creative writing abilities has motivated
me to get my very own blog now 😉