├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── main.py └── records.json /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | cloudflare-noip.code-workspace 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Devrim Yasar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cloudflare NoIP Alternative 2 | 3 | This project provides a free alternative to paid dynamic DNS services like NoIP.com. It allows you to update your DNS records on Cloudflare automatically using a free Cloudflare account and a cronjob on your computer. 4 | 5 | ## Setup 6 | 7 | 1. Clone this repository to your local machine. 8 | 9 | 2. Create a `keys.json` file in the `~/.cloudflare-noip/` directory with the following structure: 10 | 11 | ```json 12 | { 13 | "api_key": "your_cloudflare_api_key", 14 | "email": "your_cloudflare_email", 15 | "zone_ids": { 16 | "website_name1":"cloudflare_zone_id1", 17 | "website_name2":"cloudflare_zone_id2" 18 | } 19 | } 20 | ``` 21 | 22 | To get your Cloudflare API key and zone ID: 23 | 24 | - Log in to your Cloudflare account and go to the "My Profile" section. 25 | - Click on "API Tokens" and create a new token with the template " Edit zone DNS" permission. 26 | - Go to your website overview page, on the bottom right you'll see Zone ID, copy that and paste in to your keys.json 27 | 28 | 3. Create a `records.json` file in the `~/.cloudflare-noip/` directory with the following structure: 29 | 30 | ```json 31 | [ 32 | { 33 | "record_name": "sub.domain.xyz", 34 | "record_type": "A", 35 | "proxied": true 36 | "website_name": "domain.xyz" 37 | }, 38 | { 39 | "record_name": "sub.domain1.xyz", 40 | "record_type": "A", 41 | "proxied": true 42 | "website_name": "domain1.xyz" 43 | } 44 | ] 45 | ``` 46 | 47 | The `content` field will be automatically updated with the IP address of the machine running the script. 48 | 49 | 4. Set up a cronjob to run the script at the desired interval. Here are examples for Ubuntu, macOS, and Windows: 50 | 51 | **Ubuntu/Debian:** 52 | 53 | ```bash 54 | crontab -e 55 | ``` 56 | 57 | Add the following line to run the script every minute, this script will run every second for 60 times. 58 | (one HN user rightly pointed out that since it's a home server 1 second update is more appropriate; this frequency is your max downtime. Update: from this version onwards, this program will only update Cloudflare if IP changes.) 59 | 60 | ```bash 61 | */1 * * * * cd /path/to/cloudflare-noip && /usr/bin/python3 main.py 62 | ``` 63 | 64 | restart cron (optional) 65 | ```bash 66 | sudo systemctl restart cron 67 | ``` 68 | 69 | **macOS (using launchd):** 70 | 71 | 1. Create a new file in `~/Library/LaunchAgents/` called `com.example.cloudflare-noip.plist` with the following contents: 72 | 73 | ```xml 74 | 75 | 76 | 77 | 78 | Label 79 | com.example.cloudflare-noip 80 | ProgramArguments 81 | 82 | /usr/bin/python3 83 | /Users/d/Projects/cloudflare-noip/main.py 84 | 85 | StartInterval 86 | 60 87 | 88 | 89 | ``` 90 | 91 | 2. Load the launch agent: 92 | 93 | ```bash 94 | launchctl load ~/Library/LaunchAgents/com.example.cloudflare-noip.plist 95 | ``` 96 | 97 | **Windows (using Task Scheduler):** 98 | 99 | 1. Open the Task Scheduler: Press the Windows key + R, type `taskschd.msc`, and press Enter. 100 | 2. Create a new task: 101 | * General: Give the task a name and description. 102 | * Triggers: Create a new trigger with the desired interval (e.g., every minute). 103 | * Actions: Create a new action to start a program: `python.exe` with the argument `/path/to/cloudflare_noip.py`. 104 | * Conditions: Set any additional conditions as needed. 105 | 3. Save the task. 106 | 107 | The script will update the DNS records on Cloudflare with the current IP address of the machine running the script at the specified interval. 108 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import logging 4 | from logging.handlers import RotatingFileHandler 5 | import requests 6 | import urllib.request 7 | import urllib.error 8 | import urllib.parse 9 | 10 | # Set up logging with rotation 11 | log_file = '/tmp/cloudflare-noip.log' 12 | max_log_size = 1 * 1024 * 1024 # 1 MB 13 | backup_count = 3 # Keep 3 old log files 14 | 15 | handler = RotatingFileHandler(log_file, maxBytes=max_log_size, backupCount=backup_count) 16 | formatter = logging.Formatter('%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') 17 | handler.setFormatter(formatter) 18 | 19 | logger = logging.getLogger() 20 | logger.setLevel(logging.INFO) 21 | logger.addHandler(handler) 22 | 23 | # Read Cloudflare credentials 24 | credentials_path = os.path.expanduser('~/.cloudflare-noip/keys.json') 25 | if not os.path.exists(credentials_path): 26 | logger.info("Error: The file ~/.cloudflare-noip/keys.json does not exist.") 27 | logger.info("Please create the folder ~/.cloudflare-noip/keys.json with the following structure:") 28 | logger.info('''{ 29 | "api_key": "your_cloudflare_api_key", 30 | "email": "your_cloudflare_email", 31 | "zone_id": "your_cloudflare_zone_id", // deprecated, use zone_ids instead 32 | "zone_ids": { 33 | "website_name": "zone_id", 34 | "website_name2": "zone_id2", 35 | "website_name3": "zone_id3" 36 | } 37 | }''') 38 | exit(1) 39 | 40 | with open(credentials_path, 'r') as f: 41 | credentials = json.load(f) 42 | 43 | 44 | API_KEY = credentials['api_key'] 45 | EMAIL = credentials['email'] 46 | ZONE_ID = credentials['zone_id'] if 'zone_id' in credentials else None 47 | ZONE_IDS = credentials['zone_ids'] if 'zone_ids' in credentials else {} 48 | 49 | IP_FILE_PATH = '~/.cloudflare-noip/IP.txt' 50 | RECORDS_FILE_PATH = '~/.cloudflare-noip/records.json' 51 | 52 | 53 | def get_base_url(website_name=""): 54 | 55 | if website_name in ZONE_IDS: 56 | return f'https://api.cloudflare.com/client/v4/zones/{ZONE_IDS[website_name]}/dns_records' 57 | else: 58 | logger.info(f"Error: Website {website_name} not found in zone_ids, using default zone_id") 59 | return f'https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/dns_records' 60 | 61 | 62 | 63 | 64 | # Headers for authentication 65 | headers = { 66 | 'X-Auth-Email': EMAIL, 67 | 'X-Auth-Key': API_KEY, 68 | 'Content-Type': 'application/json' 69 | } 70 | 71 | def update_records(new_ip): 72 | # Read and process the input JSON file 73 | with open(RECORDS_FILE_PATH, "r") as f: 74 | records = json.load(f) 75 | 76 | for record in records: 77 | # Get proxied value from JSON, default to True if not present 78 | proxied = record.get('proxied', True) 79 | 80 | website_name = record.get('website_name', '') # Get website_name from record, default to empty string 81 | update_record(record['record_name'], record['record_type'], new_ip, proxied, website_name) 82 | 83 | 84 | def update_record(record_name, record_type, content, proxied=True, website_name=''): 85 | base_url = get_base_url(website_name) 86 | # Find the existing record 87 | response = requests.get(base_url, headers=headers, params={'name': record_name, 'type': record_type}) 88 | if not response.json()['success']: 89 | logger.info(response.json()) 90 | logger.info(f"Error: {response.json()['errors'][0]['message']}") 91 | exit(1) 92 | 93 | records = response.json()['result'] 94 | 95 | if records: 96 | record_id = records[0]['id'] 97 | update_url = f'{base_url}/{record_id}' 98 | data = { 99 | 'type': record_type, 100 | 'name': record_name, 101 | 'content': content, 102 | 'ttl': 1, # Auto TTL 103 | 'proxied': proxied 104 | } 105 | req = urllib.request.Request(update_url, data=json.dumps(data).encode(), headers=headers, method='PUT') 106 | else: 107 | # Create new record if it doesn't exist 108 | data = { 109 | 'type': record_type, 110 | 'name': record_name, 111 | 'content': content, 112 | 'ttl': 1, 113 | 'proxied': proxied 114 | } 115 | req = urllib.request.Request(base_url, data=json.dumps(data).encode(), headers=headers, method='POST') 116 | 117 | if response.status_code in [200, 201]: 118 | logger.info(f"{record_type} record {'updated' if records else 'created'} successfully for {record_name}") 119 | else: 120 | logger.info(f"Failed to {'update' if records else 'create'} {record_type} record for {record_name}. Status code: {response.status_code}") 121 | logger.info(response.text) 122 | 123 | 124 | def write_ip_to_file(ip): 125 | ip_file_path = os.path.expanduser(IP_FILE_PATH) 126 | os.makedirs(os.path.dirname(ip_file_path), exist_ok=True) 127 | with open(ip_file_path, 'w') as ip_file: 128 | ip_file.write(ip) 129 | logger.info(f"Current IP written to {ip_file_path}") 130 | 131 | def read_ip_from_file(): 132 | ip_file_path = os.path.expanduser(IP_FILE_PATH) 133 | if os.path.exists(ip_file_path): 134 | with open(ip_file_path, 'r') as ip_file: 135 | return ip_file.read().strip() 136 | else: 137 | logger.info("IP file does not exist") 138 | logger.info("Creating empty IP file") 139 | with open(ip_file_path, 'w') as ip_file: 140 | pass 141 | return None 142 | 143 | 144 | def main(): 145 | # Get the current public IP address 146 | try: 147 | response = requests.get('https://api.ipify.org') 148 | new_ip = response.text.strip() 149 | 150 | # Write the current IP to a file 151 | old_ip = read_ip_from_file() 152 | 153 | # Check if the IP has changed 154 | if old_ip != new_ip: 155 | logger.info("IP changed") 156 | update_records(new_ip) 157 | write_ip_to_file(new_ip) 158 | else: 159 | logger.info("IP is the same as before, not taking any action") 160 | 161 | 162 | # logger.info(f"Current public IP: {content}") # Uncomment if you want to log this 163 | except requests.RequestException as e: 164 | logger.info(f"Failed to get public IP: {e}") 165 | exit(1) 166 | 167 | 168 | if __name__ == "__main__": 169 | import time 170 | 171 | logger.info("Starting cloudflare-noip, this is setup to run every second for 60 seconds, you should set up your cron job to run this every minute") 172 | 173 | count = 0 174 | while count < 60: 175 | main() 176 | time.sleep(1) 177 | count += 1 -------------------------------------------------------------------------------- /records.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "record_name": "perforce.luckyrobots.xyz", 4 | "record_type": "A", 5 | "proxied": true 6 | }, 7 | { 8 | "record_name": "builds.luckyrobots.xyz", 9 | "record_type": "A", 10 | "proxied": true 11 | } 12 | ] --------------------------------------------------------------------------------