Rewrote the script into object oriented paradigm

This commit is contained in:
Louis Lacoste 2022-03-14 21:24:48 +01:00
parent fbdea4d98c
commit e2f9a72bf8

View file

@ -4,58 +4,64 @@
import requests
def retrieve_dns_IP(headers, apiUrl):
"""Retrieves the IP in the DNS record using the fqdn, rrset_name (for instance subdomain like www etc) and rrset_type (the DNS record type A, CNAME ...).
class GanDynDns:
def __init__(self, fqdn, rrset_name, rrset_type, apikey) -> None:
self.fqdn = fqdn
self.rrset_name = rrset_name
self.rrset_type = rrset_type
self.domain_record_string = f"DNS {self.rrset_type} record for {self.rrset_name}.{self.fqdn}"
self.apiUrl = f"https://api.gandi.net/v5/livedns/domains/{fqdn}/records/{rrset_name}/{rrset_type}"
self.headers = {"Authorization": f"Apikey {apikey}", 'User-Agent': 'Mozilla/5.0', "Content-Type": "application/json"}
self.update_dns_IP()
The function uses requests library and connect to Gandi.net API
def retrieve_dns_IP(self):
"""Retrieves the IP in the DNS record using the fqdn, rrset_name (for instance subdomain like www etc) and rrset_type (the DNS record type A, CNAME ...).
Returns:
retrievedDnsIp (str): string of the IP address in the DNS record"""
The function uses requests library and connect to Gandi.net API
response = requests.get(apiUrl, headers=headers)
Returns:
retrievedDnsIp (str): string of the IP address in the DNS record"""
responseJson = response.json() # IPs are stored in a list as string
retrievedDnsIp = responseJson['rrset_values'][0]
return retrievedDnsIp
response = requests.get(self.apiUrl, headers=self.headers)
def retrieve_public_IP():
"""Retrieves the public IP by connecting to ipinfo.io API
responseJson = response.json() # IPs are stored in a list as string
try:
retrievedDnsIp = responseJson['rrset_values'][0]
except KeyError as key_error:
print(f"{key_error} means the record doesn't exist, we'll return an empty string instead")
retrievedDnsIp =""
return retrievedDnsIp
Returns:
data['ip'] (str) : string of the public IP address"""
endpoint = "https://ipinfo.io/json"
response = requests.get(endpoint, verify = True)
def retrieve_public_IP(self):
"""Retrieves the public IP by connecting to ipinfo.io API
data = response.json()
return data['ip']
Returns:
data['ip'] (str) : string of the public IP address"""
endpoint = "https://ipinfo.io/json"
response = requests.get(endpoint, verify = True)
def update_dns_IP(apiUrl, headers, currentPublicIP):
"""Updates the IP in the DNS record using the IP provided (acquired by retrieve_public_IP)"""
data = {
"rrset_values": [currentPublicIP]
}
data = response.json()
return data['ip']
requests.put(url=apiUrl, headers=headers, json=data)
def ips_are_equals(self):
"""The method compares both IPs and returns a boolean for the equality test
def main():
# Defines the URL to access the API and the resource
fqdn = "example.com"
rrset_name = "@"
rrset_type = "A"
apiUrl = f"https://api.gandi.net/v5/livedns/domains/{fqdn}/records/{rrset_name}/{rrset_type}"
Returns:
(bool) : result of the IP equality test"""
self.currentPublicIP = self.retrieve_public_IP()
self.dnsIP = self.retrieve_dns_IP()
return self.currentPublicIP == self.dnsIP
# Define the headers to use for the API
apikey = "account-api-key"
headers={"Authorization": f"Apikey {apikey}", 'User-Agent': 'Mozilla/5.0', "Content-Type": "application/json"}
dnsIP = retrieve_dns_IP(headers, apiUrl)
def update_dns_IP(self):
"""Updates the IP in the DNS record using the IP provided (acquired by retrieve_public_IP) if it is different from the DNS IP"""
currentPublicIP = retrieve_public_IP()
if not self.ips_are_equals():
data = {
"rrset_values": [self.currentPublicIP]
}
print(f"{self.domain_record_string : <40} | Old IP : {self.dnsIP} replaced -> by New IP : {self.currentPublicIP}")
requests.put(url=self.apiUrl, headers=self.headers, json=data)
else:
print(f"{self.domain_record_string : <40} | {'IPs are the same.':<17}")
if dnsIP != currentPublicIP: # We need to update the A record to match our IP
update_dns_IP(apiUrl, headers, currentPublicIP)
print(f"Old IP : {dnsIP} replaced -> by New IP : {currentPublicIP}")
else:
print("IPs are the same.")
if __name__ == "__main__":
main()
main = GanDynDns("example.org", "@", "A", "your-api-key")