Salto Events Sniffer Service

Simple service on python for resend events from SALTO server to email. Salto server send messages like this and I need forward all important to tech teem.
[ 
  { 
    "EventDateTime": "2020-09-22T15:01:40",
    "OperationID": 115,
    "OperationDescription": "Low battery level",
    "UserExtID": "",
    "DoorName": "116"
  }
]
/srv/sess/server.py
import socket
import json
import smtplib

HOST = '0.0.0.0'
PORT = 9998

email_data = {
  'smtp_server': "localhost",
  'sender_email': "support@domain.com",
  'receiver_email': "support@domain.com",
}

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

def is_json(myjson):
  try:
    json_object = json.loads(myjson)
  except ValueError as e:
    return False
  return True

def mailer(message, subject, email_data=email_data):
  message = 'Subject: {}\n\n{}'.format(subject, message)

  server = smtplib.SMTP(email_data['smtp_server'])
  server.sendmail(email_data['sender_email'],email_data['receiver_email'],msg)

while True:
  conn, addr = s.accept()
  print 'Client connection accepted ', addr
  while True:
    try:
      data = conn.recv(1024)

      if is_json(data):
        for event in json.loads(data):

#          print 'Server rcvd:', repr(data)

          sbj = event['EventDateTime'] + " | " + event['OperationDescription'] + " | " + event['DoorName']
          msg = """\
From: """ + email_data['sender_email'] + """
To: """ + email_data['receiver_email'] + """
Subject: """ + sbj + """

""" + repr(event) + """ """

          if event['OperationID'] not in [17,40,41]:
            print 'SEND: ', sbj
            mailer(msg, sbj)
#          else:
#            print 'SKIP: ', msg

      else:
        print 'Wrong JSON format: ', repr(data)
        break

    except socket.error, msg:
      print 'Client connection closed', addr
      break

conn.close()
/lib/systemd/system/salto-events.service
[Unit]
Description=Salto Events Sniffer Service
After=multi-user.target

[Service]
WorkingDirectory=/srv/sess
User=apache
Type=idle
ExecStart=/usr/bin/python /srv/sess/server.py | systemd-cat
Restart=always

[Install]
WantedBy=multi-user.target

Comments

Popular posts from this blog

FreeRadius and Google Workspace LDAP

pssh (parallel-ssh) problems on Debian 10 with Python 3.7