Your IP : 216.73.216.247


Current Path : /opt/cpanel/
Upload File :
Current File : //opt/cpanel/getbalanceandmail.py

import socket
import ssl
import xml.etree.ElementTree as ET
import smtplib
from email.message import EmailMessage

# EPP server configuration
HOST = 'epp.registry.net.za'
PORT = 700
USERNAME = 'enetworks'
PASSWORD = '36ancerg9a2'

# Email alert configuration
SMTP_HOST = 'cpmail01.enetworks.co.za'
SMTP_PORT = 587
SMTP_USER = 'fduplessis@edsl.co.za'
SMTP_PASS = 'M#gadeth01'
#ALERT_TO = 'fduplessis@databcentrix.co.za,saul@enetworks.co.za, creditors@enetworks.co.za, bgordon@datacentrix.co.za'
ALERT_FROM = SMTP_USER
BALANCE_THRESHOLD = 1500

# EPP XML templates
def epp_frame(xml):
    data = xml.encode('utf-8')
    length = len(data) + 4
    return length.to_bytes(4, byteorder='big') + data

login_xml = f"""<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
  <command>
    <login>
      <clID>{USERNAME}</clID>
      <pw>{PASSWORD}</pw>
      <options>
        <version>1.0</version>
        <lang>en</lang>
      </options>
      <svcs>
        <objURI>urn:ietf:params:xml:ns:domain-1.0</objURI>
        <objURI>urn:ietf:params:xml:ns:contact-1.0</objURI>
        <svcExtension>
          <extURI>urn:ietf:params:xml:ns:secDNS-1.1</extURI>
          <extURI>http://www.unitedtld.com/epp/charge-1.0</extURI>
          <extURI>http://co.za/epp/extensions/cozadomain-1-0</extURI>
          <extURI>http://co.za/epp/extensions/cozacontact-1-0</extURI>
        </svcExtension>
      </svcs>
    </login>
    <clTRID>ABC-12345</clTRID>
  </command>
</epp>"""

balance_xml = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp:epp xmlns:epp="urn:ietf:params:xml:ns:epp-1.0"
         xmlns:contact="urn:ietf:params:xml:ns:contact-1.0"
         xmlns:cozacontact="http://co.za/epp/extensions/cozacontact-1-0">
  <epp:command>
    <epp:info>
      <contact:info>
        <contact:id>enetworks</contact:id>
      </contact:info>
    </epp:info>
    <epp:extension>
      <cozacontact:info>
        <cozacontact:balance>true</cozacontact:balance>
      </cozacontact:info>
    </epp:extension>
    <epp:clTRID>ABC-BALANCE-0001</epp:clTRID>
  </epp:command>
</epp:epp>"""

def recv_epp_response(sock):
    header = sock.recv(4)
    if len(header) < 4:
        raise Exception("Incomplete header received")
    length = int.from_bytes(header, byteorder='big')
    payload = b''
    while len(payload) < length - 4:
        chunk = sock.recv(length - 4 - len(payload))
        if not chunk:
            break
        payload += chunk
    return payload.decode('utf-8')

def extract_balance(xml_response):
    ns = {
        'epp': 'urn:ietf:params:xml:ns:epp-1.0',
        'cozacontact': 'http://co.za/epp/extensions/cozacontact-1-0'
    }
    try:
        root = ET.fromstring(xml_response)
        balance = root.find('.//cozacontact:balance', ns)
        if balance is not None:
            return float(balance.text)
        else:
            return None
    except ET.ParseError as e:
        print(f"XML parse error: {e}")
        return None

ALERT_TO = ['fduplessis@datacentrix.co.za','saul@enetworks.co.za',  'creditors@enetworks.co.za', 'bgordon@datacentrix.co.za']

def send_alert_email(balance):
    msg = EmailMessage()
    msg['Subject'] = f'EPP Account Balance Low Alert: {balance}'
    msg['From'] = ALERT_FROM
    msg['To'] = ', '.join(ALERT_TO)  # Join list to string for header
    msg.set_content(f'Your EPP account balance is low: {balance:.2f} ZAR. Please top up soon.')

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
        server.starttls()
        server.login(SMTP_USER, SMTP_PASS)
        server.send_message(msg, to_addrs=ALERT_TO)  # send_message supports to_addrs list
    print(f"Alert email sent to {', '.join(ALERT_TO)}.")

def send_email(balance):
    MAIL_TO = ['fduplessis@datacentrix.co.za','creditors@enetworks.co.za', 'bgordon@datacentrix.co.za']
    msg = EmailMessage()
    msg['Subject'] = f'EPP Account Balance Low Alert: {balance}'
    msg['From'] = ALERT_FROM
    msg['To'] = ', '.join(MAIL_TO)  # Join list to string for header
    msg.set_content(f'Your EPP account balance is: {balance:.2f} ZAR.')

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
        server.starttls()
        server.login(SMTP_USER, SMTP_PASS)
        server.send_message(msg, to_addrs=ALERT_TO)  # send_message supports to_addrs list
    print(f"Alert email sent to {', '.join(ALERT_TO)}.")

def main():
    context = ssl.create_default_context()
    with socket.create_connection((HOST, PORT)) as sock:
        with context.wrap_socket(sock, server_hostname=HOST) as ssock:
            print("Greeting:\n", recv_epp_response(ssock))

            ssock.sendall(epp_frame(login_xml))
            print("Login Response:\n", recv_epp_response(ssock))

            ssock.sendall(epp_frame(balance_xml))
            balance_response = recv_epp_response(ssock)
            print("Balance Response:\n", balance_response)

            balance = extract_balance(balance_response)
            if balance is None:
                print("Could not find balance in response.")
                return
            print(f"Current balance: {balance:.2f} ZAR")
		
            if balance < BALANCE_THRESHOLD:
                send_alert_email(balance)
            else:
                send_email(balance)

if __name__ == "__main__":
    main()