반응형
작성일: 2024년 3월 25일
Bind9 Zone 파일의 Serial 값을 변경하는 Python Script
지금 급하게 DNS 서버(Bind9)의 Serial 값을 자동 갱신하도록하는 기능이 필요해서 작성해본 Python script이다.
동작 방식을 간단하게 설명하면 이렇다.
만약 오늘이 "2024년 03월 25일"이라고 가정하면,
- 기존 Zone 파일의 Serial 값이 2024032501 이면, 2024032502 으로 끝자리면 1 증분시켜줌.
- 기존 Zone 파일의 Serial 값이 2024032401 이면, 2024032500 으로 날짜를 오늘로 변경하고 끝 2자리는 00으로 설정
아래 Script를 복사해서 바로 실행하면 잘 동작할 것이다.
$ cat update_zone_serial.py #!/usr/bin/python3 from datetime import datetime import shutil ## ## File 내용 중에서 일부 문자열을 찾아서 바꿈. ## def replace_in_file(file_path, old_str, new_str): # 파일 읽어들이기 fr = open(file_path, 'r') lines = fr.readlines() fr.close() # old_str -> new_str 치환 fw = open(file_path, 'w') for line in lines: fw.write(line.replace(old_str, new_str)) fw.close() ## ## Zone file에 있는 Serial 값을 찾기 ## NOTE: 주의할 점 ## Zone file 안에 Serial 값이 아래 포맷으로 저장되어 있어야 한다. ## ## @ IN SOA mydomain.kr root.mydomain.kr ( ## 2024032502 ; Serial ## 3600 ; Refresh ## 900 ; Update retry ## 604800 ; Expiry ## 600 ; TTL for cache name server (for 30 minutes) ## ) ## def search_old_serial(file_path): fp = open(file_path) lines = fp.readlines() fp.close() for line in lines: if line.find('Serial') > 0: words = line.split(';') old_serial = words[0].strip() return old_serial zone_file = '/var/cache/bind/mydomain.kr.zone' old_serial = search_old_serial(zone_file) curr_date = datetime.today().strftime("%Y%m%d") bool_today = old_serial.startswith(curr_date) if bool_today is True: ## Serial 값이 오늘 Update된 경우 int_old_serial = int(old_serial) new_serial = str(int_old_serial + 1) else: ## Serial 값이 며칠 전에 Update된 경우 new_serial = f"{curr_date}00" ## copy file for backup bkup_file = f"{zone_file}_{new_serial}" shutil.copy(zone_file, bkup_file) replace_in_file(zone_file, old_serial, new_serial) ## 실행 테스트 $ ./update_zone_serial.py
Bind9 Zone 파일의 Serial 값을 변경하는 Bash Script
만약, Python 인터프리터가 없는 경우라면 아래와 같이 bash 스크립트를 작성해서 실행해도 동일한 결과를 얻을 수 있다.
$ cat my-dns-zone-serial-increase.sh #!/usr/bin/env bash set -euo pipefail : ${1?"Usage: $0 <zone file>"} IFILE=$1 if [ ! -w "${IFILE}" ]; then echo "Error cannot write to ${IFILE}" exit fi if [ ! -w $(pwd) ]; then echo "Error, sed needs write permission for temp file, add w to current directory" exit fi PREV_SERIAL=$(grep -i Serial "${IFILE}" | awk '{print $1}') echo "PREV_SERIAL: ${PREV_SERIAL}" TODAY=$(date +%Y%m%d00) if [ "$PREV_SERIAL" -ge "${TODAY}" ]; then NEW_SERIAL=$((PREV_SERIAL+1)) else NEW_SERIAL=${TODAY} fi echo "NEW_SERIAL: ${NEW_SERIAL}" sed -i "s/${PREV_SERIAL}/${NEW_SERIAL}/" "${IFILE}" printf "Zone: %s [%d -> %d]\n" "${IFILE}" "${PREV_SERIAL}" "${NEW_SERIAL}" ## 실행 테스트 $ ./my-dns-zone-serial-increase.sh /var/cache/bind/mydomain.kr.zone
'Python' 카테고리의 다른 글
주기적 화면 캡처 및 OCR 적용된 PDF 파일로 변환 (나만의 eBook 만들기) (0) | 2025.01.12 |
---|---|
Python 온라인 자습서(Tutorial), Reference, Howto, API 문서 (0) | 2024.03.27 |
Python Log Class 및 예제 (0) | 2024.03.26 |
Prometheus 설치 + Python 예제 코드 (0) | 2023.06.13 |
YAML, JSON 파일 내용 비교 (변경 내역 비교) (0) | 2021.11.18 |