| September 20, 2011 8:46 pm

Note: Whenever I come across an interesting or potentially useful piece of source code, I like to make a copy and file it away. I post some of them here in the hope that they will be useful to others as well.

In my recent coding adventures, I needed to create a function to monitor the up-time of one of my Linux servers. A very simple thing (you would think), and yet, I wasn’t able to find a function in the standard library which would give me this piece of information. So … I decided to write my own.

The script below makes use of the “uptime” command (common in many Unix operating systems) to see how long the machine has been turned on. It works on both Linux and OS X computers. If I have time, I will add code for Windows as well.

FORMAT_SEC = 1
FORMAT_MIN = 2
FORMAT_HOUR = 3
FORMAT_DAY = 4

def uptime(format = FORMAT_SEC):
  """Determine how long the system has been running. Options:
  FORMAT_SEC returns uptime in seconds, FORMAT_MIN returns minutes,
  FORMAT_HOUR returns hours, FORMAT_DAY returns uptime in days."""

  def checkuptime():
    """OS specific ways of checking and returning
    the system uptime."""

    # For Linux and Mac, use "uptime" command and parse results
    if (sys.platform == 'linux2') | (sys.platform == 'darwin'):
      raw = subprocess.Popen('uptime',
        stdout=subprocess.PIPE).communicate()[0].replace(',','')
      up_days = int(raw.split()[2])

      if 'min' in raw:
        up_hours = 0
        up_min = int(raw[4])
      else:
        up_hours, up_min = map(int,raw.split()[4].split(':'))

      # Calculate the total seconds that the system has been working
      up_sec = up_days*24*60*60 + up_hours*60*60 + up_min*60
      return up_sec

  total_sec = checkuptime()

  # Get the days, hours, etc.
  if format == FORMAT_SEC: # Return seconds
    return total_sec
  if format == FORMAT_MIN: # Return minutes
    minutes = (total_sec)/(60)
    return minutes

  if format == FORMAT_HOUR: # Return hours
    hours = (total_sec)/(60*60)
    return hours

  if format == FORMAT_DAY: # Return days
    days = (total_sec)/(60*60*24)
    return days

  return -1 # If invalid option specified, return false.

Comments

No Responses to “Code Snippet: Server Uptime (Linux and Mac OS X)”

Care to comment?