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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/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 powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy