-
-
Save handsomecheung/6b809660ddc4d1d722b36e35b8818e9e to your computer and use it in GitHub Desktop.
Check the IPv4 and IPv6 address and bind to Google Cloud DNS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import time | |
import socket | |
import requests | |
from google.cloud import dns | |
# pip install google-cloud-dns requests | |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/gcp-service-account.json" # don't forget this file! | |
GET_IP_API = "https://domains.google.com/checkip" | |
GCP_PROJECT_ID = "project-XXXXXX" | |
DEFAULT_TTL = 60 | |
DOMAINS = { | |
"aaa.com.": [ | |
"home.aaa.com.", | |
"*.home.aaa.com.", | |
], | |
"bbb.me.": [ | |
"bbb.me.", | |
], | |
"ccc.net.": [ | |
"ccc.net.", | |
"*.ccc.net.", | |
], | |
} | |
def get_family4(): | |
return socket.AF_INET | |
def get_family6(): | |
return socket.AF_INET6 | |
def get_current_ip(get_family): | |
requests.packages.urllib3.util.connection.allowed_gai_family = get_family | |
r = requests.get(GET_IP_API) | |
return r.text.strip() | |
def get_current_ipv4(): | |
return get_current_ip(get_family4) | |
def get_current_ipv6(): | |
return get_current_ip(get_family6) | |
def get_ips(): | |
return get_current_ipv4(), get_current_ipv6() | |
def set_ip(zone, domain, rtype, ip): | |
records = [ | |
record for record in zone.list_resource_record_sets() if record.name == domain and record.record_type == rtype | |
] | |
if len(records) == 0: | |
add_record(zone, domain, rtype, ip) | |
else: | |
matched = False | |
for record in records: | |
if len(record.rrdatas) != 1 or record.rrdatas[0] != ip: | |
del_changes = zone.changes() | |
del_changes.delete_record_set(record) | |
del_changes.create() | |
else: | |
matched = True | |
if not matched: | |
add_record(zone, domain, rtype, ip) | |
def add_record(zone, domain, rtype, ip): | |
add_changes = zone.changes() | |
add_changes.add_record_set(zone.resource_record_set(domain, rtype, DEFAULT_TTL, [ip])) | |
add_changes.create() | |
def main(): | |
client = dns.Client(project=GCP_PROJECT_ID) | |
while True: | |
for zone in client.list_zones(): | |
for root, domains in DOMAINS.items(): | |
if zone.dns_name == root: | |
ipv4, ipv6 = get_ips() | |
for domain in domains: | |
set_ip(zone, domain, "A", ipv4) | |
set_ip(zone, domain, "AAAA", ipv6) | |
time.sleep(120) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment