Showing posts with label python sar linux memory usage formula. Show all posts
Showing posts with label python sar linux memory usage formula. Show all posts

Friday, September 21, 2012

Percentage of Memory Used with Sar and Python for Linux

I needed to get the Percent Memory Used for a Linux systems using sar.
Linux grabs all the memory even though it does not use it all so it is takes a bit more work to figure out how memory is being used.
The formula is:
((kbmemused - kbbuffers - kbcached) / (kbmemfree + kbmemused)) * 100



#!/usr/bin/env python2.7
import re
import subprocess

mcmd = "sar -r -f /xactly/apps/sar/sjcxtlyapp01s/sa20 |grep Average"

sep = re.compile('[\s]+')
sar = subprocess.Popen([mcmd],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True)
string =  sep.split(str(sar.stdout.readlines()))
memfree = "%0.2f" %  (float(string[1]) / 1024)
memused = "%0.2f" %  (float(string[2]) / 1024)
buffers = "%0.2f" %  (float(string[4]) / 1024)
cached =  "%0.2f" % (float(string[5]) / 1024)
percent_used = "%0.2f" %  (((float(memused) - float(buffers) - float(cached))  / (float(memfree) + float(memused))) * 100)
print percent_used