Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import CloudFlare
- import argparse
- import sys
- if __name__ == "__main__":
- parser = argparse.ArgumentParser()
- parser.add_argument("-e", "--email", required=True, help="The Cloudflare login email to use")
- parser.add_argument("-n", "--hostname", required=True, help="The hostname to update, e.g. mydyndns.mydomain.com")
- parser.add_argument("-k", "--api-key", required=True,
- help="The Cloudflare global API key to use. NOTE: Domain-specific API tokens will NOT work!")
- parser.add_argument("-i", "--address", required=True, help="Which address to update the record to")
- parser.add_argument("-t", "--ttl", default=60, type=int, help="The TTL of the records in seconds (or 1 for auto)")
- parser.add_argument("-r", "--record-type", default="A", help="Which record must be created [A, CNAME, TXT, etc]")
- args = parser.parse_args()
- # Initialize Cloudflare API client
- cf = CloudFlare.CloudFlare(
- email=args.email,
- token=args.api_key
- )
- # Get zone ID (for the domain). This is why we need the API key and the domain API token won't be sufficient
- zone = ".".join(args.hostname.split(".")[1:]) # domain = test.mydomain.com => zone = mydomain.com
- zones = cf.zones.get(params={"name": zone})
- if len(zones) == 0:
- print(f"Could not find CloudFlare zone {zone}, please check domain {args.hostname}")
- sys.exit(2)
- zone_id = zones[0]["id"]
- # Fetch existing A record
- a_records = cf.zones.dns_records.get(zone_id, params={"name": args.hostname, "type": "A"})
- if len(a_records): # Have an existing record
- print("Found existing record, updating...")
- a_record = a_records[0]
- # Update record & save to cloudflare
- a_record["content"] = args.ip_address
- cf.zones.dns_records.put(zone_id, a_record["id"], data=a_record)
- else: # No existing record. Create !
- print("Record doesn't existing, creating new record...")
- a_record = {}
- a_record["type"] = args.record_type
- a_record["name"] = args.hostname
- a_record["ttl"] = args.ttl # 1 == auto
- a_record["content"] = args.address
- cf.zones.dns_records.post(zone_id, data=a_record)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement