这是一个很好的多语言实现项目!我会为每种语言提供一个基本实现,包括你提到的所有功能。由于代码较长,我会分别解释每种语言的实现。
- Rust 实现
首先,创建一个新的 Rust 项目:
cargo new godaddy_ddns
cd godaddy_ddns编辑 Cargo.toml 文件,添加必要的依赖:
[package]
name = "godaddy_ddns"
version = "0.1.0"
edition = "2021"
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
config = "0.13"
log = "0.4"
env_logger = "0.10"
chrono = "0.4"现在,创建 src/main.rs 文件:
use std::time::Duration;
use std::error::Error;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use config::Config;
use log::{info, error};
use chrono::Local;
#[derive(Debug, Deserialize)]
struct Settings {
domain: String,
record: String,
api_key: String,
api_secret: String,
check_interval: u64,
}
#[derive(Serialize)]
struct DnsRecord {
data: String,
ttl: u32,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
let settings = Config::builder()
.add_source(config::File::with_name("config"))
.build()?
.try_deserialize::<Settings>()?;
let client = Client::new();
loop {
match update_dns(&client, &settings).await {
Ok(_) => info!("DNS updated successfully"),
Err(e) => error!("Failed to update DNS: {}", e),
}
tokio::time::sleep(Duration::from_secs(settings.check_interval)).await;
}
}
async fn update_dns(client: &Client, settings: &Settings) -> Result<(), Box<dyn Error>> {
let ip = get_public_ip(client).await?;
let url = format!("https://api.godaddy.com/v1/domains/{}/records/A/{}", settings.domain, settings.record);
let record = DnsRecord {
data: ip,
ttl: 600,
};
client.put(&url)
.header("Authorization", format!("sso-key {}:{}", settings.api_key, settings.api_secret))
.json(&vec![record])
.send()
.await?
.error_for_status()?;
Ok(())
}
async fn get_public_ip(client: &Client) -> Result<String, Box<dyn Error>> {
Ok(client.get("https://api.ipify.org")
.send()
.await?
.text()
.await?)
}创建一个 config.toml 文件:
domain = "yourdomain.com"
record = "@"
api_key = "your_api_key"
api_secret = "your_api_secret"
check_interval = 300运行程序:
RUST_LOG=info cargo run- Python 实现
创建一个新的 Python 项目:
mkdir godaddy_ddns_python
cd godaddy_ddns_python
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`安装必要的依赖:
pip install requests schedule python-dotenv创建 main.py 文件:
import requests
import schedule
import time
import os
import logging
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Configuration
DOMAIN = os.getenv('DOMAIN')
RECORD = os.getenv('RECORD')
API_KEY = os.getenv('API_KEY')
API_SECRET = os.getenv('API_SECRET')
CHECK_INTERVAL = int(os.getenv('CHECK_INTERVAL', 300))
def get_public_ip():
return requests.get('https://api.ipify.org').text
def update_dns():
try:
ip = get_public_ip()
url = f"https://api.godaddy.com/v1/domains/{DOMAIN}/records/A/{RECORD}"
headers = {
'Authorization': f'sso-key {API_KEY}:{API_SECRET}',
'Content-Type': 'application/json'
}
data = [{"data": ip, "ttl": 600}]
response = requests.put(url, headers=headers, json=data)
response.raise_for_status()
logging.info(f"DNS updated successfully. New IP: {ip}")
except Exception as e:
logging.error(f"Failed to update DNS: {str(e)}")
def main():
logging.info("Starting GoDaddy DDNS updater")
schedule.every(CHECK_INTERVAL).seconds.do(update_dns)
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
main()创建一个 .env 文件:
DOMAIN=yourdomain.com
RECORD=@
API_KEY=your_api_key
API_SECRET=your_api_secret
CHECK_INTERVAL=300
运行程序:
Python main. Py- TypeScript 实现
首先,初始化一个新的 Node. Js 项目:
mkdir godaddy_ddns_typescript
cd godaddy_ddns_typescript
npm init -y
npm install typescript ts-node @types/node axios dotenv
npx tsc --init创建 src/main.ts 文件:
import axios from 'axios';
import * as dotenv from 'dotenv';
import { promises as fs } from 'fs';
dotenv.config();
interface Config {
domain: string;
record: string;
apiKey: string;
apiSecret: string;
checkInterval: number;
}
async function getPublicIp(): Promise<string> {
const response = await axios.get('https://api.ipify.org');
return response.data;
}
async function updateDns(config: Config, ip: string): Promise<void> {
const url = `https://api.godaddy.com/v1/domains/${config.domain}/records/A/${config.record}`;
const headers = {
Authorization: `sso-key ${config.apiKey}:${config.apiSecret}`,
'Content-Type': 'application/json',
};
const data = [{ data: ip, ttl: 600 }];
await axios.put(url, data, { headers });
}
async function main() {
const config: Config = {
domain: process.env.DOMAIN!,
record: process.env.RECORD!,
apiKey: process.env.API_KEY!,
apiSecret: process.env.API_SECRET!,
checkInterval: parseInt(process.env.CHECK_INTERVAL || '300', 10),
};
console.log('Starting GoDaddy DDNS updater');
setInterval(async () => {
try {
const ip = await getPublicIp();
await updateDns(config, ip);
console.log(`DNS updated successfully. New IP: ${ip}`);
await fs.appendFile('ddns.log', `${new Date().toISOString()} - DNS updated. IP: ${ip}\n`);
} catch (error) {
console.error('Failed to update DNS:', error);
await fs.appendFile('ddns.log', `${new Date().toISOString()} - Error: ${error}\n`);
}
}, config.checkInterval * 1000);
}
main().catch(console.error);创建一个 .env 文件:
DOMAIN=yourdomain.com
RECORD=@
API_KEY=your_api_key
API_SECRET=your_api_secret
CHECK_INTERVAL=300
运行程序:
npx ts-node src/main.ts- Bash Shell 实现
创建一个新的 bash 脚本文件 godaddy_ddns.sh:
#!/bin/bash
# Load configuration
source config.sh
# Logging function
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> ddns.log
echo "$1"
}
# Get public IP
get_public_ip() {
curl -s https://api.ipify.org
}
# Update DNS record
update_dns() {
local ip=$1
local response
response=$(curl -s -X PUT "https://api.godaddy.com/v1/domains/${DOMAIN}/records/A/${RECORD}" \
-H "Authorization: sso-key ${API_KEY}:${API_SECRET}" \
-H "Content-Type: application/json" \
-d "[{\"data\": \"${ip}\", \"ttl\": 600}]")
if [ $? -eq 0 ]; then
log "DNS updated successfully. New IP: ${ip}"
else
log "Failed to update DNS: ${response}"
fi
}
# Main loop
main() {
log "Starting GoDaddy DDNS updater"
while true; do
ip=$(get_public_ip)
update_dns "$ip"
sleep "$CHECK_INTERVAL"
done
}
main创建一个配置文件 config.sh:
DOMAIN="yourdomain.com"
RECORD="@"
API_KEY="your_api_key"
API_SECRET="your_api_secret"
CHECK_INTERVAL=300使脚本可执行并运行:
chmod +x godaddy_ddns.sh
./godaddy_ddns.sh这些实现都包含了你要求的功能:定时执行任务、获取当前机器的实时 IP、调用 Godaddy. Com 的 API 更改相关域名地址、日志功能、利用 config 文件进行相关环境的配置。每种语言都有其特点和优势,你可以根据自己的需求和偏好选择合适的实现。