Working Ninja
2019-06-06T20:49:55
Python 2 Implementation for `echo | nc`

A situation arose where I was unable to use nc to send some metrics to a local Graphite server. Thanksfully, Python was installed (albeit, quite a dated version) that allowed me to set up a socket to send the data over the wire.

import commands
import socket
import time


def get_device_stats(device):
    # Retrieve 1 second average from `iostat` for device.
    status, output = commands.getstatusoutput('iostat 1 2 -kd -p /dev/%s | awk NR==7' % device)
    values = output.split()
    timestamp = int(time.time())

    send_metric(device, 'iops', values[1], timestamp)
    send_metric(device, 'read', values[2], timestamp)
    send_metric(device, 'write', values[3], timestamp)


def send_metric(device, metric, value, timestamp):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('1.2.3.4', 2003))
    # New-line character is important here, otherwise Graphite will not parse the sent data.
    s.sendall('disks.%s.%s.total %s %s\n' % (device, metric, value, timestamp))
    s.close()


devices = ['sda', 'sdb', 'sdc']

for device in devices:
    get_device_stats(device)