first commit

This commit is contained in:
0ceanSlim 2024-01-09 09:33:16 -05:00
commit d0ba911df5
4 changed files with 182 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
credentials.json
last_ip.txt

8
LICENSE Normal file
View File

@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2024 OceanSlim
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

51
README.md Normal file
View File

@ -0,0 +1,51 @@
# Cloudflare Dynamic DNS Updater
This Python script automatically updates your Cloudflare DNS records with your current public IP address whenever it changes.
## Features
- Automatically detects IP changes: The script checks your public IP and compares it to the last recorded IP.
- Updates all 'A' type records: If a change is detected, it updates all 'A' type DNS records in the specified zone to the new IP.
- Securely stores credentials: Cloudflare API credentials are stored in a separate JSON file for security.
- User-friendly setup: The script guides you through the initial setup process, including entering your Cloudflare credentials.
- Clear logging: The script provides informative messages about its actions, such as success or failure of DNS updates.
## Requirements
- Python 3.x
- requests library (pip install requests)
## Setup
1. Obtain Cloudflare API credentials:
- Log in to your Cloudflare account.
- Go to My Profile > API Tokens.
- Create a new API token with the Zone.Zone and DNS.Edit permissions.
- Copy the API key and your Cloudflare email address.
2. Install the required library:
``` Bash
pip install requests
```
3. Run the script:
```Bash
python update.py
```
The script will prompt you for your Cloudflare Zone ID, email, and API key if the credentials file doesn't exist.
4. (Optional) Set up a cron job or create a service or use task scheduler in Windows:
To automate the script's execution, set up a cron job to run it at regular intervals (e.g., every hour).
## Usage
- The script will automatically check for IP changes and update DNS records accordingly.
- You can manually trigger a DNS update by running the script again.
## Additional Notes
- The script stores the last recorded IP in a file named last_ip.txt.
- The script stores Cloudflare credentials in a file named credentials.json. **Keep this file secure.**
- For more advanced usage, refer to the Cloudflare API documentation: https://api.cloudflare.com/
## License
This project is licensed under the [The MIT License](https://mit-license.org/) - see the [LICENSE](LICENSE) file for details.

121
update.py Normal file
View File

@ -0,0 +1,121 @@
import requests
import os
import json
# Function to get the public IP address
def get_public_ip():
response = requests.get('https://httpbin.org/ip')
if response.status_code == 200:
return response.json().get('origin')
else:
print('Failed to fetch IP address')
return None
# Function to read the last recorded IP from a file
def read_last_ip(file_path):
if os.path.exists(file_path):
with open(file_path, 'r') as file:
return file.read().strip()
return None
# Function to save the current IP to a file
def save_current_ip(file_path, current_ip):
with open(file_path, 'w') as file:
file.write(current_ip)
# Function to update all 'A' type DNS records to current IP if it has changed
def update_dns_if_ip_changed(ip_file_path, zone_id, api_key, email):
current_ip = get_public_ip()
if not current_ip:
print("Could not retrieve current IP. Aborting DNS update.")
return
last_ip = read_last_ip(ip_file_path)
if current_ip != last_ip:
save_current_ip(ip_file_path, current_ip)
update_all_a_records(zone_id, api_key, email, current_ip)
else:
print("IP has not changed. Skipping DNS update.")
# Function to update all 'A' type DNS records to current IP
def update_all_a_records(zone_id, api_key, email, current_ip):
if not current_ip:
print("Could not retrieve current IP. Aborting DNS update.")
return
# Fetch all 'A' type DNS records for the specified zone
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records?type=A"
headers = {
"Content-Type": "application/json",
"X-Auth-Email": email,
"X-Auth-Key": api_key
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
dns_records = response.json()["result"]
for record in dns_records:
record_id = record["id"]
payload = {
"content": current_ip,
"name": record["name"],
"proxied": record["proxied"],
"type": record["type"],
"ttl": record["ttl"]
}
update_dns_record(zone_id, api_key, email, record_id, payload)
else:
print("Failed to fetch DNS records")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
# Function to update DNS record
def update_dns_record(zone_id, api_key, email, record_id, payload):
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}"
headers = {
"Content-Type": "application/json",
"X-Auth-Email": email,
"X-Auth-Key": api_key
}
response = requests.put(url, headers=headers, json=payload)
if response.status_code == 200:
print(f"DNS record for ID {record_id} updated successfully!")
print(response.json())
else:
print(f"Failed to update DNS record for ID {record_id}")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
# Check if the IP file exists and read the last recorded IP
ip_file_path = 'last_ip.txt'
# Check if the credentials file exists and read the credentials
credentials_file_path = 'credentials.json'
# If credentials file doesn't exist, prompt user for information and save it to the file
if not os.path.exists(credentials_file_path):
zone_id = input("Enter your Zone ID: ")
auth_email = input("Enter your Cloudflare email: ")
auth_key = input("Enter your Cloudflare API key: ")
credentials = {
"zone_id": zone_id,
"auth_email": auth_email,
"auth_key": auth_key
}
with open(credentials_file_path, 'w') as file:
json.dump(credentials, file)
else:
# Read credentials from the file
with open(credentials_file_path, 'r') as file:
credentials = json.load(file)
zone_id = credentials.get("zone_id")
auth_email = credentials.get("auth_email")
auth_key = credentials.get("auth_key")
# Call the update_dns_if_ip_changed function
update_dns_if_ip_changed(ip_file_path, zone_id, auth_key, auth_email)