Получить время безотказной работы/загрузки Windows с помощью PHP?


Наша биллинговая система поддерживает мониторинг сети и показывает время безотказной работы и процент загрузки, однако в скрипте статуса PHP, который они предоставляют, говорится, что это только Linux. Настройка PHP для работы с сервером 2008 не является проблемой, но я не знаю PHP. Можно ли было бы использовать этот код для работы в Windows?

<?php
/*
*************************************************************************
*                                                                       *
* WHMCompleteSolution - Client Management, Billing & Support System     *
* Copyright (c) 2007-2008 WHMCS. All Rights Reserved,                   *
* Release Date: 12th December 2008                                      *
* Version 3.8.1 Stable                                                  *
*                                                                       *
*************************************************************************
*                                                                       *
* Email: [email protected]                                                 *
* Website: htttp://www.whmcs.com                                        *
*                                                                       *
*************************************************************************

This file can be uploaded to each of your linux web servers in order to
display current load and uptime statistics for the server in the Server
Status page of the WHMCS Client Area and Admin Area Homepage

*/

error_reporting(0);

if (ini_get('disable_functions')) {
    $disabled_funcs=array_map('trim',explode(',',ini_get('disable_functions')));
}

$action=$_GET["action"];

if ($action=="phpinfo") {
} else {
    $users[0]="Unavailable";
    $users[1]="--";
    $loadnow="Unavailable";
    $load15="--";
    $load30="--";
    if (in_array('exec',$disabled_funcs)) {
        $load=file_get_contents("/proc/loadavg");
        $load=explode(' ',$load);
        $loadnow=$load[0];
        $load15=$load[1];
        $load30=$load[2];
    } else {
        $reguptime=trim(exec("uptime"));
        if ($reguptime) {
            if (preg_match("/, *(\d) (users?), .*: (.*), (.*), (.*)/",$reguptime,$uptime)) {
                $users[0]=$uptime[1];
                $users[1]=$uptime[2];
                $loadnow=$uptime[3];
                $load15=$uptime[4];
                $load30=$uptime[5];
            }
        }
    }
    if (in_array('shell_exec',$disabled_funcs)) {
        $uptime_text=file_get_contents("/proc/uptime");
        $uptime=substr($uptime_text,0,strpos($uptime_text," "));
    } else {
        $uptime=shell_exec("cut -d. -f1 /proc/uptime");
    }
    $days=floor($uptime/60/60/24);
    $hours=str_pad($uptime/60/60%24,2,"0",STR_PAD_LEFT);
    $mins=str_pad($uptime/60%60,2,"0",STR_PAD_LEFT);
    $secs=str_pad($uptime%60,2,"0",STR_PAD_LEFT);
    $phpver=phpversion();
    if(function_exists("mysql_get_client_info()")) $mysqlver=mysql_get_client_info();
    if(function_exists("zend_version()")) $zendver=zend_version();
    echo "<load>$loadnow</load>\n";
    echo "<uptime>$days Days $hours:$mins:$secs</uptime>\n";
    echo "<phpver>$phpver</phpver>\n";
    echo "<mysqlver>$mysqlver</mysqlver>\n";
    echo "<zendver>$zendver</zendver>\n";
}

?>
Author: hakre, 2011-10-05

5 answers

Эта версия объединяет некоторые из предложенных здесь идей и некоторые из моих собственных в файл, который должен работать примерно одинаково как в *nix, так и в Windows. Также исправлено несколько вопиющих ошибок/ленивых кодов в оригинале.

Будет не работать в Windows, если exec() отключен. Я не вижу никакого способа обойти это.

Дай мне знать, как у тебя дела.

<?php

/*
*************************************************************************
*                                                                       *
* WHMCompleteSolution - Client Management, Billing & Support System     *
* Copyright (c) 2007-2008 WHMCS. All Rights Reserved,                   *
* Release Date: 12th December 2008                                      *
* Version 3.8.1 Stable                                                  *
*                                                                       *
*************************************************************************
*                                                                       *
* Email: [email protected]                                                 *
* Website: htttp://www.whmcs.com                                        *
*                                                                       *
*************************************************************************

  Modified by DaveRandom, Sept 2011

This file can be uploaded to each of your linux/Windows web servers in
order to display current load and uptime statistics for the server in the
Server Status page of the WHMCS Client Area and Admin Area Homepage

*/

error_reporting(0);

if (ini_get('disable_functions')) {
  $disabled_funcs = array_map('trim',explode(',',ini_get('disable_functions')));
}

$action = (isset($_GET["action"])) ? $_GET["action"] : NULL;

if ($action == "phpinfo") {

  // Seems as though something is missing here - maybe phpinfo() ?

} else {

  // Stuff that works everywhere
  $phpver = phpversion();
  $mysqlver = (function_exists("mysql_get_client_info")) ? mysql_get_client_info() : '';
  $zendver = (function_exists("zend_version")) ? zend_version() : '';

  // Default values
  $users[0] = $loadnow = "Unavailable";
  $users[1] = $load15 = $load30 = "--";
  $uptime_str = '';

  if (strpos(strtolower(PHP_OS),'win') !== FALSE) {

    // For Windaz
    if (!in_array('exec',$disabled_funcs)) {

      set_time_limit(150); // 'systeminfo' command can take a while...

      $uptime = exec('systeminfo | find "System Up"');
      $parts = explode(':',$uptime);
      $parts = array_pop($parts);
      $parts = explode(',',trim($parts));
      foreach (array('days','hours','mins','secs') as $k => $v) {
        $parts[$k] = explode(' ',trim($parts[$k]));
        $$v = ($k) ? str_pad(array_shift($parts[$k]),2,'0',STR_PAD_LEFT) : array_shift($parts[$k]);
      }
      $uptime_str = "$days Days $hours:$mins:$secs";

      exec('typeperf -sc 1 "\Processor(*)\% Processor Time"',$result);
      for ($i = 0; trim($result[$i]) == ''; $i++) continue;
      $parts = explode(',',$result[++$i]);
      $loadnow = (is_numeric($loadnow = trim(trim(array_pop($parts)),'"\''))) ? $loadnow : 'Unavailable';

    }

  } else {

    // For *nix

    if (in_array('exec',$disabled_funcs)) {
      $load = file_get_contents("/proc/loadavg");
      $load = explode(' ',$load);
      $loadnow = $load[0];
      $load15 = $load[1];
      $load30 = $load[2];
    } else if (($reguptime = trim(exec("uptime"))) && preg_match("/, *(\\d) (users?), .*: (.*), (.*), (.*)/",$reguptime,$uptime)) {
      $users[0] = $uptime[1];
      $users[1] = $uptime[2];
      $loadnow = $uptime[3];
      $load15 = $uptime[4];
      $load30 = $uptime[5];
    }
    if (in_array('shell_exec',$disabled_funcs)) {
      $uptime_text = file_get_contents("/proc/uptime");
      $uptime = substr($uptime_text,0,strpos($uptime_text," "));
    } else {
      $uptime = shell_exec("cut -d. -f1 /proc/uptime");
    }
    $days = floor($uptime/60/60/24);
    $hours = str_pad($uptime/60/60%24,2,"0",STR_PAD_LEFT);
    $mins = str_pad($uptime/60%60,2,"0",STR_PAD_LEFT);
    $secs = str_pad($uptime%60,2,"0",STR_PAD_LEFT);
    $uptime_str = "$days Days $hours:$mins:$secs";

  }

  echo "<load>$loadnow</load>\n";
  echo "<uptime>$uptime_str</uptime>\n";
  echo "<phpver>$phpver</phpver>\n";
  echo "<mysqlver>$mysqlver</mysqlver>\n";
  echo "<zendver>$zendver</zendver>\n";

}
 1
Author: DaveRandom, 2011-10-05 17:07:39

Вы можете попробовать следующее в окне Windows, чтобы получить время безотказной работы системы в строке:

$uptimeData = shell_exec('systeminfo | find "Time:"');

Если вам нужны данные в другом формате, вам, вероятно, потребуется использовать регулярное выражение, но похоже, что ваш скрипт просто сбрасывает информацию в xml-файл.

 0
Author: Andrew, 2011-10-05 15:21:29

Для бесперебойной работы вы можете выполнить вызов exec() для systeminfo | find "System Up", а затем обработать вывод.

Для загрузки вы можете запустить wmic /namespace:\\root\cimv2 path Win32_Processor get LoadPercentage, хотя при этом будет получена только текущая загрузка процессора, а не средние исторические значения.

В любом случае вам придется определить операционную систему (см. PHP_OS) и выполните правильные команды для системы, в которой работает ваш скрипт.

 0
Author: Justin ᚅᚔᚈᚄᚒᚔ, 2011-10-05 15:27:22
<?php echo shell_exec("systeminfo |find 'Up Time'");?>

Но вам нужно установить максимальное время выполнения php не менее 120 (выполнение этой команды занимает некоторое время)

 0
Author: Vlad S., 2011-10-05 15:30:41

Попробуйте Это:

Код: https://miladworkshop.ir/paste/Uzype9

<?php
/*
    This Code Create By Milad Maldar ( miladworkshop )
    Website     : https://miladworkshop.ir
    Telegram    : @miladworkshop
*/

function service_uptime()
{
    $uptime_sys     = exec('net statistics server | find "Statistics since"');
    $uptime_sys     = str_replace("Statistics since ", "", $uptime_sys);

    $uptime_dte     = exec('date | find "The current date is:"');
    $uptime_dte     = str_replace("The current date is: Sat ", "", $uptime_dte);
    $uptime_dte     = explode("/", $uptime_dte);

    $uptime_tme     = exec('time | find "The current time is:"');
    $uptime_tme     = str_replace("The current time is: ", "", $uptime_tme);
    $uptime_tme     = explode(":", $uptime_tme);

    $uptime_date    = explode("/", $uptime_sys);
    $uptime_time    = explode(":", $uptime_sys);

    $system_time    = strtotime("{$uptime_dte[2]}-{$uptime_dte[0]}-{$uptime_dte[1]} {$uptime_tme[0]}:{$uptime_tme[1]}:{$uptime_tme[2]}");

    $y              = substr($uptime_date[2], 0, 4);
    $m              = ($uptime_date[0] < 10) ? "0". $uptime_date[0] : $uptime_date[0];
    $d              = ($uptime_date[1] < 10) ? "0". $uptime_date[1] : $uptime_date[1];
    $i              = ($uptime_time[1] < 10) ? "0". $uptime_time[1] : $uptime_time[1];
    $h              = (substr($uptime_time[0], strpos($uptime_time[0], "{$y} ") + 5) < 10) ? "0". substr($uptime_time[0], strpos($uptime_time[0], "{$y} ") + 5) : substr($uptime_time[0], strpos($uptime_time[0], "{$y} ") + 5);

    if (substr($uptime_sys, -2) == "PM")
    {
        $h = str_replace("01", "13", $h);
        $h = str_replace("02", "14", $h);
        $h = str_replace("03", "15", $h);
        $h = str_replace("04", "16", $h);
        $h = str_replace("05", "17", $h);
        $h = str_replace("06", "18", $h);
        $h = str_replace("07", "19", $h);
        $h = str_replace("08", "20", $h);
        $h = str_replace("09", "21", $h);
        $h = str_replace("10", "22", $h);
        $h = str_replace("11", "23", $h);
        $h = str_replace("12", "00", $h);
    }

    $up                 = strtotime("{$y}-{$m}-{$d} {$h}:{$i}:00");

    $string             = "";
    $seconds            = $system_time - $up;

    $days               = intval(intval($seconds) / (3600*24));
    $hours              = (intval($seconds) / 3600) % 24;
    $minutes            = (intval($seconds) / 60) % 60;
    $seconds            = (intval($seconds)) % 60;

    if($days> 0)        { $string .= "{$days} days ";       }
    if($hours > 0)      { $string .= "{$hours} hours ";         }
    if($minutes > 0)    { $string .= "{$minutes} minutes ";     }
    if ($seconds > 0)   { $string .= "{$seconds} seconds";  }

    return $string;
}

echo service_uptime();
?>
 0
Author: miladworkshop, 2018-06-23 07:40:20