Ruby:检测 Fedora 机器开机时间
感觉就像我之前访问过 stackoverflow 100 次一样。总是找到好的解决方案,但现在我陷入困境。
我想监控电脑每天运行多长时间。这是用 Ruby 编写的程序的一部分,在 Fedora 机器上运行。
之前我在Windows下做过类似的事情,可以使用WndProc捕获相关的电源事件。然而,对于 Fedora(或一般的 Linux),我找不到一个好的钩子来检测开机和关机/挂起/休眠/....
任何建议都将受到高度赞赏。
谢谢, jayrock
编辑:似乎我还不清楚我想要实现什么。实际上不仅希望获得有关当前正常运行时间的信息,还希望获得有关过去正常运行时间的信息。因此我应该知道“计算机在过去 14 天内已运行 x 小时”或类似信息。
另一个补充是,例如 last
命令也不起作用 - 它不会显示系统是否进入休眠或挂起状态。
feels like I visited stackoverflow 100 times before. Always found good solutions, but now I'm stuck.
I want to monitor how long a computer runs every day. This is part of a program written in Ruby, running on a Fedora machine.
Previously I did similar things under Windows, where it is possible to catch the related power events using WndProc. However, with Fedora (or Linux in general) I don't find a good hook to detect power-on and power-off/suspend/hibernate/....
Any suggestion is highly appreciated.
Thanks,
jayrock
EDIT: Seems I haven't been clear in what I want to achieve. Actually want to have information about not only the current uptime but also past uptimes. Thus I should know "the computer has been running for x hours over the last 14 days" or similar.
Another addition is that e.g. the last
command doesn't do the job either - it doesn't show if the system goes to hibernate or suspend.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能想要解析
last
命令的输出,该命令记录用户的登录。如果伪用户reboot
“已登录”,您就知道系统已重新启动。 (这对 Ubuntu 有效;也许 Fedora 使用不同的名称,例如boot
。)可能有更直接的界面;谷歌搜索
ruby + utmp
。utmp
文件通常位于/var/run
中,记录last
命令报告的数据。You may want to parse the output from the
last
command, which logs users' logins. If the pseudo-userreboot
"logged in", you know the system was rebooted. (This is valid for Ubuntu; maybe Fedora uses a different name, such asboot
.)There may be a more direct interface; Google around for
ruby + utmp
. Theutmp
file, commonly in/var/run
, records the data that thelast
command reports.我不知道 ruby 的具体细节,但 linux 中有一个命令正常运行时间。
我认为在 ruby 中你需要使用 System
所以它会像
system 'uptime'
然后你可以解析它的结果
I don't know the ruby specifics but there is a command uptime in linux.
I think in ruby you need to use System
so it would be something like
system 'uptime'
Then you can parse the results of that
您可以使用反引号,例如
uptime
尽管在此答案框中,StackOverflow 将它们视为代码样式。
You would use backticks like
uptime
StackOverflow regards them as code styles though in this answer box.