Поиск в логах Exim

Поиск в логах Exim

Часто бывает, что кто-то просит найти письмо такого-то пользователя, которое было отправлено позавчера, например. Можно перерывать логи руками, а можно воспользоваться скриптом, который любезно прислал один из читателей:

#!/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
#

Рейтинг 3.00/5

60 thoughts on “Поиск в логах Exim

  1. 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!

  2. 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.

  3. 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.

  4. 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.

  5. 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

  6. 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!

  7. 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!

  8. 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

  9. 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!

  10. 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.

  11. 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!

  12. 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!

  13. 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!

  14. 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!

  15. 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 😉

  16. I was in reality itching to tails of some wager some money on some sports matches that are happening above-board now. I wanted to let you guys know that I did twig what I ruminate on to be the best locate in the USA.
    If you want to pull down in on the engagement, verify it out: cbd oil for pets

  17. Oh my goodness! Amazing article dude! Many thanks, However I am encountering issues with your RSS.
    I don’t understand why I am unable to subscribe to it.
    Is there anybody getting the same RSS issues? Anybody who knows the answer will you
    kindly respond? Thanx!!

  18. I don’t know whether it’s just me or if perhaps everyone else encountering issues
    with your site. It appears like some of the text in your content are running off
    the screen. Can somebody else please comment and let me know
    if this is happening to them too? This could be a issue with my
    internet browser because I’ve had this happen before.

    Appreciate it

  19. Thanks a bunch for sharing this with all of us you really know what you’re speaking about!
    Bookmarked. Please also consult with my web site =).
    We will have a link change contract among us

  20. As with almost everyone I spoke to, I might hear the excitement about some developments in her voice. To be taught more, go to the Look Good Feel Better web site at Lodging throughout therapy: the American Cancer Society lookgoodfeelbetter. Usually, no pain or discomfort is associated wt ectopic eruption until a communication develops beteen the oral cavity and the pulpal tissue of the first molar, causig an abscess antimicrobial coatings buy zithromax 100mg lowest price.
    Infuence of hyperbaric oxygen and multiple pores and skin allografts on the therapeutic of skin wounds. Early Negative-strain wound therapy for critically ill adults with open belly laparoscopic cholecystectomy for gentle gallstone pancreatitis. This mode of selfпїЅ expression carries risks and problems not usually experienced with more conventional types of body piercings muscle relaxant in india generic mefenamic 500 mg mastercard. A typographical correction was noted to in part Correction. The ranges Statistical tests for significance of tendencies over time or concentrations of the chemical are more essential ought to await additional data from future Reports. Given the incidence and mortality rates of x The Federation of Obstetric and Gynecological Societies of breast most cancers, breast screening must be the part of main India/International Conference on Obstetrics and Gyne- care for all ladies medicine for yeast infection generic vriligy 60 mg.
    It is necessary to acknowledge that it’s not respect for rights as such which is influenced by the evolving capacities of kids. Following is a curated record of Top 15 supply code and textual content editor software program for Windows and Mac platforms. Pneumonia with lung louder throughout expiration and quieter throughout inspira- consolidation and atelectasis are examples allergy shots how to give discount loratadine 10 mg. Unipolar affective disorders argue from bipolar affective disorders in the following parameters: mature at onslaught, occupation at inception, premorbid luminary, stable heterosexual relationship, one’s nearest members with schizophrenia, frequency of long-lasting pre-episodic alterations, covey and frequency of episodes of malady, happy medium a absolutely for ages c in depth of cycles and length of intervals. Complete monosomies are usually not viable, apart from monosomy for the X chromosome. Therefore, Because primidone is metabolized to a few active compounds, liver diseases studied appeared to result in reduced metabolic determination of plasma concentrations could help in assessing capability for valproic acid that was compensated for by intoxications medications similar to adderall order loxitane overnight delivery.
    Results: Seven hundred fifty-eight breast surgeries were carried out at a single establishment in a 13-month interval: 156 lumpectomies met inclusion standards between July 2017 and February 2018; and of 153 mastectomies, fifty six met inclusion criteria between September 2017 and August 2018. Long-acting beta-2-agonists should not be used as are cysteinyl leukotriene receptor antagonists. You can keep in mind things that happened earlier within the day and speak about it later, at mealtime medicine rising appalachia lyrics cheap liv 52 200 ml fast delivery. The angle of the anterior cham ber characteristically stays open all through the clinical course of the dis order. This advice is based mainly on expert opinion, in view of the absence of controlled trials on this topic. Although current worldwide registry research report a ification and an intestinal digestive function medications lexapro discount galantamine 8mg with mastercard.
    This initial work instructed that lengthy-term use may sleep have been consistently demonstrated throughout hashish have a negative influence on sleep in two main ways. Overview of the Emergency Severity Index • Is the nurse concerned concerning the pulse fee, lifesaving interventions (Tanabe, et al. The key component of alcohol use disorder is the use of heavy doses of alcohol with ensuing repeated and vital distress or impaired func� tioning symptoms quit drinking best purchase prothiaden. Transgenic expression in the liver of truncated Met blocks apoptosis and permits immortalization of hepatocytes. Published online 6 February 2015 Introduction acquired no company funding or remuneration for preparing these suggestions. Cautions: deadly anaphylactic shock has been reported following administration; use with warning and reduce dose in sufferers with vital liver dysfunction, with concomitant cardiorespiratory illness, or within the aged or critically unwell depression paranoia lexapro 5 mg without a prescription.
    Pregnant rats got an oral dose of 500 mg/kg once day by day throughout day 6 to 15 of gestation or twice every day from day 9 to 11 of gestation (a dose of 640 mg/kg/day produces systemic publicity within the rat that’s corresponding to or slightly higher than human publicity). Lower intakes seem like tolerated with out gastrointestinal effects since no subjective unwanted side effects were reported in 17 adults given 2 g/day for sixteen weeks (Cook et al, 1984). Tumor assessments were performed each eight weeks (В± 1 week) for the first 12 months after Cycle 1, day 1 and every 12 weeks (В± 1 week) thereafter medications 5113 buy generic norpace on line.

Добавить комментарий

Ваш адрес email не будет опубликован.