Advertisement
mrbits

Untitled

Aug 9th, 2022
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import CloudFlare
  3. import argparse
  4. import sys
  5.  
  6. if __name__ == "__main__":
  7.     parser = argparse.ArgumentParser()
  8.     parser.add_argument("-e", "--email", required=True, help="The Cloudflare login email to use")
  9.     parser.add_argument("-n", "--hostname", required=True, help="The hostname to update, e.g. mydyndns.mydomain.com")
  10.     parser.add_argument("-k", "--api-key", required=True,
  11.                         help="The Cloudflare global API key to use. NOTE: Domain-specific API tokens will NOT work!")
  12.     parser.add_argument("-i", "--address", required=True, help="Which address to update the record to")
  13.     parser.add_argument("-t", "--ttl", default=60, type=int, help="The TTL of the records in seconds (or 1 for auto)")
  14.     parser.add_argument("-r", "--record-type", default="A", help="Which record must be created [A, CNAME, TXT, etc]")
  15.     args = parser.parse_args()
  16.  
  17.     # Initialize Cloudflare API client
  18.     cf = CloudFlare.CloudFlare(
  19.         email=args.email,
  20.         token=args.api_key
  21.     )
  22.     # Get zone ID (for the domain). This is why we need the API key and the domain API token won't be sufficient
  23.     zone = ".".join(args.hostname.split(".")[1:])  # domain = test.mydomain.com => zone = mydomain.com
  24.     zones = cf.zones.get(params={"name": zone})
  25.     if len(zones) == 0:
  26.         print(f"Could not find CloudFlare zone {zone}, please check domain {args.hostname}")
  27.         sys.exit(2)
  28.     zone_id = zones[0]["id"]
  29.  
  30.     # Fetch existing A record
  31.     a_records = cf.zones.dns_records.get(zone_id, params={"name": args.hostname, "type": "A"})
  32.     if len(a_records):  # Have an existing record
  33.         print("Found existing record, updating...")
  34.         a_record = a_records[0]
  35.         # Update record & save to cloudflare
  36.         a_record["content"] = args.ip_address
  37.         cf.zones.dns_records.put(zone_id, a_record["id"], data=a_record)
  38.     else:  # No existing record. Create !
  39.         print("Record doesn't existing, creating new record...")
  40.         a_record = {}
  41.         a_record["type"] = args.record_type
  42.         a_record["name"] = args.hostname
  43.         a_record["ttl"] = args.ttl  # 1 == auto
  44.         a_record["content"] = args.address
  45.         cf.zones.dns_records.post(zone_id, data=a_record)
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement