cloudflare.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import json
  2. from os import environ, getenv
  3. from time import sleep
  4. from requests import get, put
  5. def get_request_header(email, api_key):
  6. return {
  7. "X-Auth-Email": email,
  8. "X-Auth-Key": api_key,
  9. "Content-Type": "application/json"
  10. }
  11. def print_error(result):
  12. for error in result["errors"]:
  13. print(Exception(error))
  14. def get_zone_id(headers, host_name):
  15. params = {"name": host_name}
  16. response = get("https://api.cloudflare.com/client/v4/zones", params=params, headers=headers)
  17. result = response.json()
  18. if result["success"]:
  19. return result["result"][0]["id"]
  20. else:
  21. print_error(result)
  22. return None
  23. def get_record_id(headers, zone_id, host_name):
  24. params = {"name": host_name}
  25. response = get(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records", params=params,
  26. headers=headers)
  27. result = response.json()
  28. if result["success"]:
  29. return result["result"][0]["id"]
  30. else:
  31. print_error(result)
  32. return None
  33. def update_dns(headers, zone_id, record_id, host_name, ip, ttl, proxy):
  34. data = {"type": "A", "name": host_name, "content": ip, "ttl": ttl, "proxied": proxy}
  35. response = put(f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}",
  36. data=json.dumps(data), headers=headers)
  37. result = response.json()
  38. if result["success"]:
  39. return True
  40. else:
  41. print_error(result)
  42. return False
  43. def get_ip():
  44. return get(getenv("IP_ECHO", "http://ipecho.net/plain")).text # http://icanhazip.com Also works
  45. def update(ip):
  46. email = environ["EMAIL"]
  47. api_key = environ["API"]
  48. host_name = environ["HOST"]
  49. headers = get_request_header(email, api_key)
  50. zone_id = get_zone_id(headers, host_name)
  51. if zone_id is None:
  52. return
  53. record_id = get_record_id(headers, zone_id, host_name)
  54. if record_id is None:
  55. return
  56. ttl = int(getenv("TTL", "1"))
  57. proxy = getenv("PROXY", "True").lower() == "true"
  58. result = update_dns(headers, zone_id, record_id, host_name, ip, ttl, proxy)
  59. if result:
  60. print(f"Update Success:{host_name}({ip})")
  61. else:
  62. print(Exception(f"Update Fail:{host_name}({ip})"))
  63. def main():
  64. ip = None
  65. new_ip = get_ip()
  66. while True:
  67. if ip != new_ip:
  68. update(new_ip)
  69. ip = new_ip
  70. sleep(int(getenv("WAIT", 300)))
  71. new_ip = get_ip()
  72. if __name__ == "__main__":
  73. main()