madebychung

서버 타임을 맞춰보자 본문

카테고리 없음

서버 타임을 맞춰보자

mdchung 2024. 9. 24. 15:50

서버 타임을 안맞췄다....

그래서 로그 시간이 아주 지 멋대로 이다

그래서 chrony를 이용해 서버 타임을 맞추고자 한다.

 

vi set_crrunt_time.sh

#!/bin/bash

# 기본 선택을 "y"로 처리하는 함수
read_default_yes() {
    local prompt="$1"
    local input
    read -p "$prompt (y/n) [y]: " input
    if [[ -z "$input" || "$input" =~ ^[Yy]$ ]]; then
        echo "y"
    else
        echo "n"
    fi
}

# Chrony 또는 NTP 설치 확인 및 설치 함수
check_and_install_time_sync() {
    if ! command -v chronyd &> /dev/null && ! command -v ntpd &> /dev/null; then
        echo "Chrony나 NTP가 설치되어 있지 않습니다. chrony 패키지를 찾고 설치를 진행합니다."
        echo "Chrony or NTP is not installed. Searching for and installing the chrony package."

        # 시스템에서 chrony 패키지를 검색 (find 명령어 사용)
        chrony_rpm=$(find / -name "chrony-*.rpm" 2>/dev/null | head -n 1)
        if [[ -z "$chrony_rpm" ]]; then
            echo "chrony 패키지를 찾을 수 없습니다. 먼저 chrony 패키지를 시스템에 다운로드하세요."
            echo "Could not find the chrony package. Please download the chrony package to your system first."
            exit 1
        else
            echo "다음 경로에서 chrony 패키지를 찾았습니다: $chrony_rpm"
            echo "Found chrony package at: $chrony_rpm"
            echo "chrony 패키지를 설치합니다."
            echo "Installing chrony package."
            sudo dnf install -y "$chrony_rpm"
            if [ $? -eq 0 ]; then
                echo "Chrony가 성공적으로 설치되었습니다."
                echo "Chrony has been successfully installed."
            else
                echo "Chrony 설치에 실패했습니다. 수동으로 설치를 시도해주세요."
                echo "Failed to install Chrony. Please try to install it manually."
                exit 1
            fi
        fi
    else
        echo "Chrony 또는 NTP가 이미 설치되어 있습니다."
        echo "Chrony or NTP is already installed."
    fi
}

# 경고 문구 출력 (한국어와 영어)
echo -e "\033[1;31m경고: 이미 애플리케이션이 실행 중인 경우, 시간 변경이 애플리케이션에 영향을 줄 수 있습니다.\033[0m"
echo -e "\033[1;31m신중하게 설정하시기 바랍니다!\033[0m"
echo -e "\033[1;31mWarning: Changing the system time can affect running applications.\033[0m"
echo -e "\033[1;31mPlease proceed with caution!\033[0m"

# Chrony 또는 NTP 설치 확인 및 설치
check_and_install_time_sync

# 현재 시스템 시간 출력 (한국어/영어)
current_time=$(date "+%Y-%m-%d %H:%M:%S")
echo "현재 시스템 시간 / Current system time: $current_time"

# 시간 설정 방법 선택 (한국어/영어)
echo "시간 설정 방법을 선택하세요 / Choose time setting method:"
echo "1) 수동 설정 / Manual setting"
echo "2) NTP 서버 사용 / Use NTP server"
echo "3) 현재 시간을 유지 / Keep current time"
read -p "선택 / Choice (1/2/3): " method

if [[ "$method" == "1" ]]; then
    # 수동으로 시간 설정 (한국어/영어)
    echo "서버 시간을 새로 설정합니다. 아래 형식에 맞게 입력해주세요."
    echo "Please enter the new server time in the format below."
    echo "형식 / Format: YYYY-MM-DD HH:MM:SS (예 / Example: $current_time)"

    # 시간 입력 받기 (엔터 입력 시 현재 시간을 기본값으로 설정)
    read -p "새로운 시간을 입력하세요 / Enter new time [현재 시간 / Current time]: " new_time

    if [[ -z "$new_time" ]]; then
        new_time=$current_time
    fi

    # 입력받은 시간 유효성 체크 (정규 표현식)
    if [[ "$new_time" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}$ ]]; then
        echo "입력한 시간이 유효합니다 / The entered time is valid: $new_time"
        if [[ $(read_default_yes "이 시간으로 서버 시간을 설정하시겠습니까? / Would you like to set the server time to this time?") == "y" ]]; then
            # 서버 시간 설정
            sudo date -s "$new_time"
            sudo hwclock --systohc
            echo "서버 시간이 $new_time으로 설정되었습니다."
            echo "The server time has been set to $new_time."
        else
            echo "시간 설정이 취소되었습니다. / The time setting has been canceled."
        fi
    else
        echo "입력한 시간 형식이 유효하지 않습니다. 스크립트를 다시 실행해주세요."
        echo "The entered time format is invalid. Please run the script again."
        exit 1
    fi

elif [[ "$method" == "2" ]]; then
    # NTP 서버를 통해 시간 설정 (한국어/영어)
    while true; do
        echo "NTP 서버 선택 / Select NTP server:"
        echo "1) time.bora.net - 한국 인터넷 제공업체에서 운영하는 NTP 서버"
        echo "2) time.kriss.re.kr - 한국 표준과학연구원에서 제공하는 NTP 서버"
        echo "3) time.windows.com - Microsoft에서 제공하는 NTP 서버"
        echo "4) time.nist.gov - 미국 NIST에서 제공하는 공인 NTP 서버"
        echo "5) 사용자 정의 NTP 서버 입력 / Enter a custom NTP server"

        read -p "번호를 선택하세요 / Please select a number (1-5): " choice

        case $choice in
            1) ntp_server="time.bora.net" ;;
            2) ntp_server="time.kriss.re.kr" ;;
            3) ntp_server="time.windows.com" ;;
            4) ntp_server="time.nist.gov" ;;
            5) read -p "NTP 서버 주소를 입력하세요 / Enter NTP server address: " ntp_server ;;
            *) echo "잘못된 선택입니다. 다시 선택해주세요. / Invalid selection. Please choose again."; continue ;;
        esac

        echo "선택된 NTP 서버 / Selected NTP server: $ntp_server"

        # UDP 123번 포트로 NTP 서버와의 통신 여부 확인 (nc 사용)
        if nc -zv -u $ntp_server 123 &>/dev/null; then
            echo "$ntp_server의 UDP 123번 포트로 통신이 성공했습니다."
            echo "Communication to $ntp_server via UDP port 123 was successful."
            break
        else
            echo "$ntp_server의 UDP 123번 포트로 통신이 실패했습니다. 다시 선택해주세요."
            echo "Communication to $ntp_server via UDP port 123 failed. Please choose again."
        fi
    done

    # Chrony 또는 NTP 설정 파일 수정
    if [[ -f /etc/chrony.conf ]]; then
        # Chrony가 설치된 경우
        sudo sed -i '/^server/d' /etc/chrony.conf
        echo "server $ntp_server iburst" | sudo tee -a /etc/chrony.conf
        sudo systemctl restart chronyd
        echo "Chrony를 통해 $ntp_server로 동기화되었습니다."
        echo "Synchronized with $ntp_server using Chrony."
    elif [[ -f /etc/ntp.conf ]]; then
        # NTP가 설치된 경우
        sudo sed -i '/^server/d' /etc/ntp.conf
        echo "server $ntp_server" | sudo tee -a /etc/ntp.conf
        sudo systemctl restart ntpd
        echo "NTP를 통해 $ntp_server로 동기화되었습니다."
        echo "Synchronized with $ntp_server using NTP."
    else
        echo "Chrony나 NTP 설정 파일을 찾을 수 없습니다. 설치를 확인해주세요."
        echo "Could not find Chrony or NTP configuration file. Please check the installation."
        exit 1
    fi

elif [[ "$method" == "3" ]]; then
    # 현재 시간 유지
    echo "현재 시간을 유지합니다. 스크립트를 종료합니다."
    echo "Keeping the current time. Exiting the script."
    exit 0
else
    echo "잘못된 선택입니다. 스크립트를 다시 실행해주세요."
    echo "Invalid selection. Please run the script again."
    exit 1
fi

# 마지막으로 현재 시간 출력 (한국어/영어)
new_current_time=$(date "+%Y-%m-%d %H:%M:%S")
echo "설정 후 현재 시스템 시간 / Current system time after setting: $new_current_time"

# Cron에 추가할지 여부 확인 (한국어/영어)
if [[ $(read_default_yes "시간을 주기적으로 확인하고 동기화하도록 cron 작업을 설정하시겠습니까? / Would you like to set up a cron job to periodically check and synchronize the time?") == "y" ]]; then
    # Crontab에 추가할 스크립트 경로 설정
    script_path=$(realpath "$0")

    # Cron 작업 추가 (매 시간마다 스크립트 실행)
    (crontab -l 2>/dev/null; echo "0 * * * * $script_path") | crontab -

    echo "Cron 작업이 추가되었습니다. 매 시간마다 스크립트가 실행됩니다."
    echo "Cron job has been added. The script will run every hour."
else
    echo "Cron 작업 추가가 취소되었습니다. / Cron job addition has been canceled."
fi

time.tar
0.36MB