Мониторинг транков Asterisk с уведомлением о проблеме по почте

Хочу привести пример php скрипта, который я иногда использую для мониторинга транков. Я помещаюего в cron с интервалом в 15 минут. После срабатывания он проверит транки. Если есть не работающий – дает паузу в 20 секунд. Снова проверяет состояние транков. Если ничего не изменилось – перегружаем модуль chan_sip в asterisk. И если это не могло – шлем email с отчетом по почте, указанной в переменной $report_email.
Скрипт не мой лично – но нареканий в работе у меня нет.

#!/usr/bin/php -q
<!--?php 

// set up the email address to receive the alert email
$report_email = '[email protected]';

$state = wots_up();
echo $state;

if ($state == 'ok')
{
 //если все нормально - прекращаем выполнение
 exit;
}
else
{
 //если нет - пауза в 20 секунд и снова проверяем
 sleep(20);
 $state = wots_up();
 $have_done = "We have retried in 20 seconds.\r\n";
}

if ($state == 'ok')
{
 //если все нормально - прекращаем выполнение
 exit;
}
else
{
 $have_done .= "Trying to reload the sip channels.\r\n";
 $have_done .= shell_exec('/usr/sbin/asterisk -rx "module reload chan_sip"');
 sleep(20);
 $have_done .= "Reloaded sip channels and waited 20 seconds.\r\n";
 $state = wots_up();
}

if ($state == 'ok')
{
 //wipes the sweat
 exit;
}

$status = "$have_done\r\n====have done above, the current status: ====\r\n$status";

if ($state == 'requesting')
{
 send_alert_email('Trunk has been sending registrating requests', $status);
}
elseif ($state == 'empty')
{
 send_alert_email('Voip trunk registration status is empty', $status);
}
elseif ($state == 'no_auth')
{
 send_alert_email('No Authentication is reported, wrong password?', $status);
}
elseif ($state == 'unregistered')
{
 send_alert_email('We have Unregistered trunk', $status);
}
elseif ($state == 'failed')
{
 send_alert_email('We have Registration failed trunk', $status);
}
elseif ($state == 'auth_sent')
{
 send_alert_email('We have trunk with Auth. Sent status', $status);
}
elseif ($state == 'rejected')
{
 send_alert_email('We have trunk with Rejected status', $status);
}
else
{
 send_alert_email('Trunk status is not registered', "$state\r\n\r\n$status");
}

function wots_up()
{
 global $status;

 //Берем статусы транков
 $status = shell_exec('/usr/sbin/asterisk -rx "sip show registry"');

 if (strlen(trim($status)) == 0)
 {
  return 'empty';
 }

 $lines = explode("\n", str_replace("\r\n", "\n", trim($status)));

 for ($i = 1; $i < count($lines) - 1; $i++)
 {
  //echo "line $i " .  $lines[$i] . "\n";
  if (strpos($lines[$i], 'Request Sent') !== false)
  {
   return 'requesting';
  }
  elseif(strpos($lines[$i], 'No Authentication') !== false)
  {
   return 'no_auth';
  }
  elseif(strpos($lines[$i], 'Unregistered') !== false)
  {
   return 'unregistered';
  }
  elseif (strpos($lines[$i], 'Failed') !== false)
  {
   return 'failed';
  }
  elseif (strpos($lines[$i], 'Auth. Sent') !== false)
  {
   return 'auth_sent';
  }
  elseif (strpos($lines[$i], 'Rejected') !== false)
  {
   return 'rejected';
  }
  elseif (strpos($lines[$i], 'Timeout') !== false)
  {
   return 'timeout';
  }
  elseif (strpos($lines[$i], 'Unknown') !== false)
  {
   return 'unknown';
  }

  $temp = preg_split('/\s+/', $lines[$i]);
  if (!isset($temp[3]))
  {
   return "Can not extract Reg State for this line: " . $lines[$i];
  }
  elseif ($temp[3] <--> "Registered")
  {
   return "Unknown Reg state for this line: " . $lines[$i];
  }
 }

 return 'ok';
}

function send_alert_email($subject, $email_content = '')
{
 global $report_email;
 mail($report_email, $subject, $email_content);
}

?&gt;

44 комментария к “Мониторинг транков Asterisk с уведомлением о проблеме по почте

  1. I was pretty pleased to uncover this page. I need to to thank you for ones time due to this fantastic read!! I definitely really liked every part of it and I have you book-marked to look at new stuff in your web site.

  2. I?d have to check with you below. Which is not something I generally do! I take pleasure in checking out a blog post that will make people think. Additionally, many thanks for allowing me to comment!

  3. I?m impressed, I should say. Truly hardly ever do I run into a blog site that?s both informative and also entertaining, as well as let me inform you, you have actually hit the nail on the head. Your suggestion is exceptional; the concern is something that not nearly enough people are talking smartly about. I am really happy that I came across this in my search for something relating to this.

  4. Please let me know if you’re looking for a writer for your site. You have some really great articles and I feel I would be a good asset. If you ever want to take some of the load off, I’d really like to write some material for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Thank you!

  5. Hello there, I discovered your blog by the use of Google while searching for a comparable subject, your
    website came up, it appears to be like great.
    I have bookmarked it in my google bookmarks.

    Hi there, just became alert to your weblog thru Google, and located that it’s really informative.
    I am gonna watch out for brussels. I will be grateful if you proceed this in future.
    Many folks will probably be benefited from
    your writing. Cheers! 3aN8IMa cheap flights

  6. Good article. I learn something more difficult on various blogs daily. It will always be promoting to review content from other writers and also practice a something from their store. I?d favor to utilize some with the material on my blog whether you don?t mind. Natually I?ll give you a web link on your web blog. Thanks for sharing.

  7. It’s the best time to make some plans for the future and it’s time to be happy.
    I have read this post and if I could I want to suggest you few interesting things or suggestions.
    Perhaps you could write next articles referring to this article.
    I wish to read even more things about it!

  8. Youre so great! I don’t suppose Ive check out anything such as this prior to. So great to locate someone with some original thoughts on this subject. realy thank you for starting this up. this web site is something that is needed online, a person with a little originality. useful task for bringing something new to the net!

  9. Attractive element of content. I just stumbled upon your site and in accession capital to say that I acquire in fact enjoyed account your blog
    posts. Anyway I’ll be subscribing in your augment and even I fulfillment you get admission to consistently fast.

  10. After research a few of the blog posts on your site now, and also I really like your method of blogging. I bookmarked it to my book mark web site checklist and will be checking back quickly. Pls look into my web site too and let me understand what you assume.

  11. I think this is among the such a lot significant information for me.

    And i’m satisfied studying your article. However
    should commentary on few general issues, The site taste is ideal, the
    articles is in reality excellent : D. Just right activity, cheers

  12. I feel that is among the most important info for me.
    And i am happy studying your article. However should
    statement on some general things, The site taste is perfect, the articles is truly excellent : D.
    Just right job, cheers

  13. There are some intriguing points in this article but I don?t recognize if I see every one of them facility to heart. There is some credibility however I will certainly take hold viewpoint until I check out it better. Great write-up, many thanks and we want more! Added to FeedBurner also

  14. Can I just state what an alleviation to find someone who actually knows what theyre speaking about on the internet. You certainly understand how to bring an issue to light and make it essential. More people require to read this and also understand this side of the story. I angle believe youre not more popular because you most definitely have the gift.

  15. Have you ever considered about including a little bit more than just your articles? I mean, what you say is valuable and everything. Nevertheless imagine if you added some great pictures or videos to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could undeniably be one of the best in its niche. Wonderful blog!

  16. Do you have a spam issue on this site; I also am a blogger, and I was wanting to know your situation; many of us have created some nice methods and we are looking to swap strategies with others, please shoot me an email if interested.

  17. Have you ever considered about adding a little bit more than just your articles? I mean, what you say is important and everything. Nevertheless imagine if you added some great visuals or videos to give your posts more, “pop”! Your content is excellent but with images and clips, this site could undeniably be one of the most beneficial in its niche. Wonderful blog!

  18. My programmer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on several websites for about a year and am worried about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!

  19. An impressive share! I have just forwarded this onto a co-worker who had been doing a little research on this. And he in fact bought me lunch because I found it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanx for spending the time to talk about this matter here on your internet site.

  20. Right here is the perfect website for anyone who hopes to find out about this topic. You know so much its almost tough to argue with you (not that I personally will need to…HaHa). You definitely put a fresh spin on a topic that has been discussed for a long time. Excellent stuff, just wonderful!

  21. I am really enjoying the theme/design of your web site. Do you ever run into any internet browser compatibility issues? A small number of my blog audience have complained about my blog not working correctly in Explorer but looks great in Firefox. Do you have any suggestions to help fix this issue?

  22. The next occasion I read a weblog, I’m hoping that it doesnt disappoint me around brussels. After all, It was my choice to read, but I just thought youd have some thing fascinating to express. All I hear is really a number of whining about something that you could fix when you werent too busy searching for attention.

  23. Couldn´t be written any kind of far better. Reading this post reminds me of my old room mate! He always kept talking about this. I can forward that article to him. Extremely sure he definitely will possess a excellent read. Thanks for sharing!

  24. Youre so trendy! I do not expect Ive read anything such as this prior to. So nice to discover someone with some original ideas on this subject. realy thanks for beginning this up. this web site is something that is needed online, somebody with a little creativity. helpful task for bringing something new to the net!

  25. The following time I check out a blog site, I really hope that it doesn’t disappoint me as long as this. I mean, I understand it was my choice to review, yet I actually believed youd have something interesting to state. All I listen to is a number of whining concerning something that you can fix if you werent as well active searching for attention.

Оставить ответ

Ваш адрес email не будет опубликован. Обязательные поля помечены *