Skip to content

Instantly share code, notes, and snippets.

@jfinstrom
Created November 8, 2023 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfinstrom/a769fc77d6fb8c4147b0f2ab45e2113b to your computer and use it in GitHub Desktop.
Save jfinstrom/a769fc77d6fb8c4147b0f2ab45e2113b to your computer and use it in GitHub Desktop.
This script checks if asterisk is running by a specific user and has not reset since last run.
<?php
/**
* Copyright 2023 James Finstrom
* File: asteriskcheck
*
* Description: This PHP file contains the functionality for checking if asterisk is
* running by a specific user and has not reset since last run.
*
* Author: James Finstrom
*
* Contact: github@g3p0.xyz
*
* Date: 11/08/2023
*
* @license BSD-3-Clause https://opensource.org/license/bsd-3-clause/
*
*/
/* Configuration */
$emailAddress = "your_email@example.com";
$fromAddress = "from@example.com";
$asteriskUser = "asterisk";
$commandToCheck = "/usr/sbin/asterisk -f -U asterisk -G asterisk -vvvg -c";
$logFile = "last_run_status.txt";
function checkProcess() {
$psOutput = shell_exec("ps aux");
$psLines = explode("\n", $psOutput);
foreach ($psLines as $line) {
if (strpos($line, $asteriskUser) === 0 && strpos($line, $commandToCheck) !== false) {
$timeInfo = preg_split('/\s+/', $line);
if (count($timeInfo) >= 9) {
return $timeInfo[8];
}
}
}
return null;
}
function main() {
if (file_exists($logFile)) {
$lastRunStatus = trim(file_get_contents($logFile));
} else {
$lastRunStatus = "0";
}
$currentStatus = checkProcess();
if ($currentStatus) {
if ($lastRunStatus !== "1") {
/* Send an email since the process has started or changed */
$subject = "Asterisk Process Started or Changed";
$message = "Asterisk process has started or changed.";
$headers = "From: " . $fromAddress;
mail($emailAddress, $subject, $message, $headers);
}
} else {
if ($lastRunStatus !== "0") {
/* Send an email since the process has terminated or reset */
$subject = "Asterisk Process Terminated or Reset";
$message = "Asterisk process has terminated or reset.";
$headers = "From: " . $fromAddress;
mail($emailAddress, $subject, $message, $headers);
}
}
/* Update the last run status in the log file */
file_put_contents($logFile, $currentStatus ? "1" : "0");
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment