Linux get hard disk statistics using Python
Today I wanted to collect disk usage information and send them to a remote server script. I used df command to collect disk usage information and Python to send them to a remote server. Note that the remote server script uses basic authentication. So, here is the script which does the dirty job:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# used the following links:
# http://docs.python.org/2/library/re.html
# http://docs.python.org/2/library/httplib.html
# http://mozgovipc.blogspot.gr/2012/06/python-http-basic-authentication-with.html
# http://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output
import sys
import subprocess
import re
import httplib
import urllib
import base64
import logging
authUser = "myuser"
authPass = "mypadd"
logFile = "./sendDiskData.log"
def main():
# initialise logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename=logFile,
filemode='w')
# execute df -H
p = subprocess.Popen(['df', '-H'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# get stdout and stderr
out, err = p.communicate()
# find /dev/vda1
mato = re.findall(r'/dev/[sv]da.*',out,re.MULTILINE)
# execute hostname
p = subprocess.Popen(['hostname'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# get stdout and stderr
out, err = p.communicate()
# get Hostname
hostName = out
# check if object is None (null)
if mato:
diskData = re.sub(r'^(.dev..da[^ \t]*)[ \t]*([0-9]*[.]*[0-9]*[MKG])[ \t]*([0-9]*[.]*[0-9]*[MKG])[ \t]*([0-9]*[.]*[0-9]*[MKG])[ \t]*([0-9]*[.]*[0-9]*[%]).*',r'\1,\2,\3,\4,\5',mato[0])
# create basic authentication header
auth = base64.encodestring('%s:%s' % (authUser, authPass)).replace('\n', '')
# create request params
params = urllib.urlencode({'hostname': hostName, 'diskdata': diskData})
# add Basic Authentication Header
headers = {"Authorization": "Basic %s" % auth}
# create url string
diavUrl = "/clusterdisks.php?%s" % params
try:
conn = httplib.HTTPConnection("manios.org")
# perform request
conn.request("GET", diavUrl , None, headers)
response = conn.getresponse()
logging.info("Disk data sent. Code:%s , Reason:%s",response.status, response.reason)
except HTTPException :
#logging.error("Failed to send disk data of %s: with error : %s",hostName,e1)
logging.error("Failed to send disk data of %s",hostName)
sys.exit(1)
# Exit with success
sys.exit(0)
if __name__ == '__main__':
main()
Comments