Simple Heartbeat System

The purpose of this system is to make sure a group of computers can keep track of each other’s well being. If one or more systems is unable to respond to a network request, we immediately assume something went wrong.

This combination of client-server scripts has been written in Python. All it does is this: a client sends a message periodically to the server. The server echoes back whatever the client sent. If the client has any problems connecting with the server or does not receive an echo, it sends an email to whoever you want to and then quits.

I tried to make the client script keep running after sending an email but then decided against it. The reason was that I would prefer to manually check the problem and fix it rather than have the client try to fix it itself.

The code used here was inspired by: (a) Sending email in python; (b) Simple echo server; and (c) Simple echo client.

You will need two files on the client side: and message.txt where message.txt will contain the message to be emailed. The server will only need and no other file.

import socket
host = ''
port = 550000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while (1):
	client, address = s.accept()
	data = client.recv(size)
	if data:

import socket
import time
import smtplib
smtpserver = ''
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = ''  # for SMTP AUTH, set SMTP username here
smtppass = 'password'  # for SMTP AUTH, set SMTP password here
RECIPIENTS = ['','','']
MESSAGE_TO_SEND = 'message.txt'
host = ''
port = 550000
size = 1024
while (1):
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.send('Hello, world')
		data = s.recv(size)
		print 'Received from ', host, ': ', data
		time.sleep (10)
		print 'There has been some problem with the connection... Sending email(s) to ', RECIPIENTS
		mssg = open(MESSAGE_TO_SEND, 'r').read()
		session = smtplib.SMTP(smtpserver)
			session.login(smtpuser, smtppass)
		smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
		if smtpresult:
			errstr = ""
			for recip in smtpresult.keys():
				errstr = """Could not deliver mail to: %s
				Server said: %s
				%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
			raise smtplib.SMTPException, errstr


Subject: Heartbeat Problem

The server on this IP is not responding to heartbeat. Please investigate.

Please remember to put an empty line between the “Subject” line and the actual message in message.txt.

I assumed the authors wanted their code to be used freely because they had posted this code for the sole purpose of teaching people like myself how to do this stuff. If this is not the case, I would be glad to remove your copyrighted content.

Comments are closed.

%d bloggers like this: