require 'win32ole' require 'socket' require 'parsedate' module Sys class Uptime class Error < StandardError; end VERSION = '0.5.0' # Returns the boot time as a Time object. # def self.boot_time(host=Socket.gethostname) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => e raise Error, e else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) results.each{ |ole| time_array = ParseDate.parsedate(ole.LastBootupTime) return Time.mktime(*time_array) } end end # Calculates and returns the number of days, hours, minutes and # seconds the system has been running as a colon-separated string. # def self.uptime(host=Socket.gethostname) arr = self.get_dhms(host) return arr.join(":") end # Calculates and returns the number of days, hours, minutes and # seconds the system has been running as a four-element Array. # def self.dhms(host=Socket.gethostname) return self.get_dhms(host) end # Returns the total number of days the system has been up. # def self.days(host=Socket.gethostname) return self.get_dhms(host).first end # Returns the total number of hours the system has been up. # def self.hours(host=Socket.gethostname) return self.get_dhms(host)[1] end # Returns the total number of minutes the system has been up. # def self.minutes(host=Socket.gethostname) return self.get_dhms(host)[2] end # Returns the total number of seconds the system has been up. # def self.seconds(host=Socket.gethostname) return self.get_dhms(host).last end private def self.get_dhms(host) cs = "winmgmts://#{host}/root/cimv2" begin wmi = WIN32OLE.connect(cs) rescue WIN32OLERuntimeError => e raise Error, e else query = "select LastBootupTime from Win32_OperatingSystem" results = wmi.ExecQuery(query) now = Time.now results.each{ |ole| time_array = ParseDate.parsedate(ole.LastBootupTime) boot_time = Time.mktime(*time_array) break } seconds = (now - boot_time).to_i days = (seconds / 86400).to_i seconds -= days * 86400 hours = seconds / 3600 seconds -= hours * 3600 minutes = seconds / 60 seconds -= minutes * 60 return [days,hours,minutes,seconds] end end end end