Skip to content

Instantly share code, notes, and snippets.

@msafadieh
Created September 19, 2019 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msafadieh/d75a5cc6cad20736248988b85971c7ca to your computer and use it in GitHub Desktop.
Save msafadieh/d75a5cc6cad20736248988b85971c7ca to your computer and use it in GitHub Desktop.
a very small client for Namecheap API that I needed for automation
from xml.etree import ElementTree as ET
import requests
NAMECHEAP_URL = "https://api.namecheap.com/xml.response"
class NamecheapClient:
def __init__(self, api_key, api_user, user_name, client_ip):
self.api_key = api_key
self.api_user = api_user
self.user_name = user_name
self.client_ip = client_ip
@property
def base_payload(self):
return {
"ApiUser": self.api_user,
"UserName": self.user_name,
"ApiKey": self.api_key,
"ClientIp": self.client_ip
}
def make_request(self, payload):
for k, v in self.base_payload.items():
payload[k] = v
response = requests.get(NAMECHEAP_URL, params=payload)
root = ET.fromstring(response.text)
if root.get("Status") != "OK":
raise Exception("API Error." + response.text)
return root
def get_hosts(self, domain, email_type=False):
payload = {}
payload['Command'] = 'namecheap.domains.dns.getHosts'
self.add_domain(domain, payload)
root = self.make_request(payload)
if root.get("Status") != "OK":
raise Exception
hosts = [{
"Address": raw_host.get("Address"),
"HostName": raw_host.get("Name"),
"MXPref": raw_host.get("MXPref"),
"RecordType": raw_host.get("Type"),
"TTL": raw_host.get("TTL")
} for raw_host in root[3][0]]
if email_type:
hosts.append(root[3][0].get("EmailType"))
return hosts
def add_domain(self, domain, payload):
sld, tld = domain.split(".")
payload["TLD"] = tld
payload["SLD"] = sld
def set_hosts(self, domain, hosts, email_type):
payload = {}
payload['EmailType'] = email_type
payload["Command"] = "namecheap.domains.dns.setHosts"
self.add_domain(domain, payload)
for index, host in enumerate(hosts, 1):
for key, value in host.items():
payload[key + str(index)] = value
self.make_request(payload)
return True
def add_host(self, domain, host):
current_hosts = self.get_hosts(domain, True)
email_type = current_hosts[-1]
new_hosts = current_hosts[:-1]
new_hosts.append(host)
return self.set_hosts(domain, new_hosts, email_type)
def delete_host(self, domain, host_name):
current_hosts = self.get_hosts(domain, True)
email_type = current_hosts[-1]
new_hosts = list(filter(lambda host: host["HostName"] != host_name, current_hosts[:-1]))
return self.set_hosts(domain, new_hosts, email_type)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment