【问题标题】:Get Linux System Last Boot Time获取 Linux 系统上次启动时间
【发布时间】:2012-09-12 11:45:13
【问题描述】:

我需要从 PHP 脚本获取上次系统启动时间,最好是 UNIX 时间戳格式。

是否有任何文件在启动时创建或修改?我可以读取文件的修改时间。

系统类型是CentOS。

【问题讨论】:

  • 标准 unix 方式是who -r,(或who -b),它报告运行级别的最后更改,存储在 wtmp/utmp 中。但也许这太老套了。
  • @wildplasser,谢谢你,正如他们所说,你每天都能学到新东西。
  • 我不确定who -b。可能是 linuxism,就像 /proc/* 一样。
  • @wildplasser -b 在 SunOS 上可用,但至少在 FreeBSD 上可用。

标签: php linux centos


【解决方案1】:

/proc/正常运行时间

此文件包含两个数字:系统的正常运行时间(秒)和空闲进程所花费的时间(秒)。

<?php

function get_boottime() {
    $tmp = explode(' ', file_get_contents('/proc/uptime'));

    return time() - intval($tmp[0]);
}

echo get_boottime() . "\n";

【讨论】:

  • 应该补充一点,只需从time() 中减去正常运行时间,就会得到作为 unix 时间戳的启动时间。 (可能需要对值进行四舍五入/取整 - 因为 /proc/uptime 可以包含小数)
【解决方案2】:

试试这个:

方法一

<?php
$uptime = trim( shell_exec( 'uptime' ) );
// output is 04:47:32 up 187 days,  5:03,  1 user,  load average: 0.55, 0.55, 0.54

$uptime = explode( ',', $uptime );
$uptime = explode( ' ', $uptime[0] );

$uptime = $uptime[2] . ' ' . $uptime[3]; // 187 days
?>

方法二

<?php
$uptime = trim( file_get_contents( '/proc/uptime' ) );
$uptime = explode( ' ', $uptime[0] );

echo $uptime[0];//uptime in seconds
?>

希望对你有帮助。

【讨论】:

  • 你的“方法 1”什么都不做。 (在 5 分钟前完成编辑)而且你的“方法 2”没有回答这个问题。他想要的是上次启动时间,而不是当前的正常运行时间。
  • 第一种方法可以使用strtotime转换成时间戳。
【解决方案3】:
who -b # in command-line

为您提供上次启动时间 (http://www.kernelhardware.org/find-last-reboot-time-and-date-on-linux/)

exec ( $command , $output ); // in PHP

执行一个shell命令

strtotime(); // in PHP

将任何英文文本日期时间描述解析为 Unix 时间戳

所以这将为您提供 Linux 系统的上次启动时间:

// in PHP
exec('who -b',$bootTime);//where $bootTime is an array, each line returned by the command is an element of the array
$result = strtotime($bootTime[1]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2021-08-18
    • 2013-12-30
    相关资源
    最近更新 更多