엄지월드

[홈서버] DNS 자동 매핑 처리 본문

Server&DevOps

[홈서버] DNS 자동 매핑 처리

킨글 2025. 9. 16. 16:33

홈서버의 경우 고정 아이피가 아닌 경우가 대부분이라 아이피가 매번 바뀔 수 있기 때문에 DNS와 IP를 매칭시켜주어야 한다.

duckdns.org에 들어가서 domain을 생성한 후 token을 생성하고 아래와 같이 sh 파일을 만들어 스케줄러 돌리면 된다.

 

파일 생성

vi duck.sh

 

파일 내용

#!/bin/bash
#
# Simple shell script to run DuckDNS update
# Requires curl to be installed
#

# Configuration variables
# Set your domain or comma separated list of domains and subdomains
# (for example: mytestdomain.duckdns.org,other.duckdns.org)
DOMAIN="domain.duckdns.org"
# Set your token as per your account for example from the duckdns.org home page
TOKEN="111111-296e-4c07-9cab-222222"

# Check this file is actually being executed directly
[[ "$BASH_SOURCE" == "$0" ]] || return

# Check for root if using system-wide configuration
if [[ $EUID != 0 ]]
then
    echo 'ERROR: Requires root privileges (sudo).'
    exit 1
fi

# Check if curl is installed
if ! command -v curl &> /dev/null
then
    echo "ERROR: 'curl' command not found. Please install curl."
    exit 1
fi

# Get IP addresses, filter to current, filter to IPv4 & IPv6
WAN_IPS="$(ip -o -f inet addr | awk '{print $4}' | cut -d/ -f1)"

if [[ -z "$WAN_IPS" ]]
then
    echo 'ERROR: No public IP address was found for WAN interface.'
    exit 2
fi

for CURRENT_IP in $WAN_IPS
do
    # Check IPv4 and IPv6
    if [[ "$CURRENT_IP" == *.* ]] # Is this IPv4?
    then
        echo -n "Updating with IPv4 address ($CURRENT_IP)... "
        URL="https://www.duckdns.org/update?domains=$DOMAIN&token=$TOKEN&ip=$CURRENT_IP"
        RES="$(curl -s -L "$URL")"
    elif [[ "$CURRENT_IP" == *:* ]] # Is this IPv6?
    then
        echo -n "Updating with IPv6 address ($CURRENT_IP)... "
        URL="https://www.duckdns.org/update?domains=$DOMAIN&token=$TOKEN&ipv6=$CURRENT_IP"
        RES="$(curl -s -L "$URL")"
    fi

    if [[ "$RES" == "OK" ]]
    then
        echo 'OK'
    elif [[ "$RES" == "KO" ]]
    then
        echo 'ERROR: Server returned KO'
    else
        echo "ERROR: Unknown server response ($RES)"
    fi
done

# Re-check server status for this IP to confirm changes
echo -n 'Checking server status... '
CHECK_URL="https://www.duckdns.org/update?domains=$DOMAIN&token=$TOKEN&check=true"
CHECK_RES="$(curl -s -L "$CHECK_URL")"
if [[ "$CHECK_RES" == *"$CURRENT_IP"* ]]
then
    echo 'OK'
else
    echo "ERROR: Could not verify that IP ($CURRENT_IP) has been updated."
fi

echo 'Done.'

 

crontab 설정 진입

sudo crontab -e

 

맨 아래에 아래 명령어 추가

0 * * * * /home/kingle/duckdns/duck.sh > /var/log/duckdns_hourly_update.log 2>&1

0 * * * *: "매 시간 0분(정각)에 실행"
첫 번째 0: 매 시 정각 (분)
두 번째 *: 매 시간 (시)
세 번째 *: 매일 (일)
네 번째 *: 매월 (월)
다섯 번째 *: 매 요일 (요일)

Comments