스크립트

[스크립트] AWS 클라우드프론트 아이피를 가져와 zonefile을 생성하시오

변군이글루 2022. 11. 11. 16:35
반응형

AWS 클라우드프론트 아이피를 가져와 zonefile을 생성하시오

 

aws 서울 리전 클라우드프론트 아이피를 가져와서 현재 iplist.txt 파일에 있는 아이피 리스트와 대역을 비교하여 일치하면 iplist.txt에 있는 아이피로 A 레코드를 등록하고 zonefile을 생성하시오

cat iplist.txt
13.210.67.230

서울 리전의 클라우드프론트에 대한 모든 IPv4 주소 가져오기

curl -Ssf https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-2") | select(.service=="CLOUDFRONT") | .ip_prefix'
$ curl -Ssf https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-2") | select(.service=="CLOUDFRONT") | .ip_prefix'
13.210.67.128/26
13.54.63.128/26

ztest.sh 파일 생성

#!/bin/bash

### AWS CLOUDFRONT IP
curl -Ssf https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-2") | select(.service=="CLOUDFRONT") | .ip_prefix' > aws_cloudfront_ip.txt
cloudfrontIp=`cat aws_cloudfront_ip.txt`

### LOCAL DNS IP
localDnsip=`cat iplist.txt`

dnszonefilemake() {
    cat <<EOF> cf.sangchul.kr.zone
\$TTL 60
@                       IN  SOA     @   rname.invalid. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
                        NS      @
                        A       127.0.0.1
                        AAAA    ::1
EOF
}

cloudfrontipcheck() {
    for aip in $cloudfrontIp
    do
        for lip in $localDnsip
        do 
            # echo ${aip%.*}
            # echo ${lip%.*}
            if [ ${aip%.*} == ${lip%.*} ]
            then
                echo "True"
                echo -e "cf.sangchul.kr.\t\tA\t${lip}" >> cf.sangchul.kr.zone
            else
                echo "False"
            fi
        done
    done
}

dnszonefilemake
cloudfrontipcheck
$ cat aws_cloudfront_ip.txt
13.210.67.128/26
13.54.63.128/26
$ cat cf.sangchul.kr.zone
$TTL 60
@                       IN  SOA     @   rname.invalid. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
                        NS      @
                        A       127.0.0.1
                        AAAA    ::1
cf.sangchul.kr.         A       13.210.67.230

 


모든 IPv4 주소 가져오기

https://ip-ranges.amazonaws.com/ip-ranges.json 

 

특정 리전의 모든 IPv4 주소 가져오기

curl -Ssf https://ip-ranges.amazonaws.com/ip-ranges.json | jq '.prefixes[] | select(.region=="ap-southeast-2")'

특정 서비스의 대한 모든 IPv4 주소 가져오기

curl -Ssf https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.service=="CLOUDFRONT") | .ip_prefix'

특정 리전의 특정 서비스에 대한 모든 IPv4 주소 가져오기

curl -Ssf https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-2") | select(.service=="CLOUDFRONT") | .ip_prefix'

python으로 재작성

- github : https://github.com/anti1346/awscloudfrontip

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import os, sys
import requests
import ipaddress
from pathlib import Path

ip_ranges = requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').json()['prefixes']
cloudfront_ips = [item['ip_prefix'] for item in ip_ranges if (item["service"] == "CLOUDFRONT" and item["region"] == "ap-northeast-2")]

### 클라우드프론트 서브넷
cloudfront_seoul_subnet=[]
for ip in cloudfront_ips:
    cloudfront_seoul_subnet.append(ip)

### 클라우드프론트 아이피 리스트를 리스트(list)에 저장
cloudfrontiplist=[]
for ip in cloudfront_seoul_subnet:
    net4 = ipaddress.ip_network(str(ip))
    # print(net4.hosts)
    for x in net4.hosts():
        cloudfrontiplist.append(format(ipaddress.IPv4Address(x)))
# print(cloudfrontiplist)


### iplist.txt 파일을 읽어 리스트(list)에 저장
iplist=[]
with open('iplist.txt', 'r') as filehandle:
    for line in filehandle:
        curr_place = line[:-1]
        iplist.append(curr_place)
# print(iplist)


### iplist.txt의 아이피 리스트와 클라우드프론트 아이피 리스트 비교
recodelist=[]
for a in iplist:
    for b in cloudfrontiplist:
        if a == b:
            recodelist.append(a)
print(recodelist)

#############################################################################
#############################################################################
#############################################################################

### zonefile 템플릿 및 백업
dnszonefile = 'sangchul.kr.zone'
path = Path(dnszonefile)
if path.is_file():
    print(f'{dnszonefile} 파일이 존재합니다.')
    os.system('copy sangchul.kr.zone sangchul.kr.zone.bk')
else:
    print(f'{dnszonefile} 파일이 존재하지 않습니다')
    os.system('copy zonefile sangchul.kr.zone')


### sangchul.kr zonefile 생성
os.system('copy zonefile sangchul.kr.zone')
dnszonefile = open('sangchul.kr.zone', 'a')
if len(recodelist) == 0:
    print("기존 레코드 유지, A 레코드 : %s" %len(recodelist))
    os.system('copy sangchul.kr.zone.bk sangchul.kr.zone')
else:
    for a in recodelist:
        print("A 레코드 추가 : %s 추가 생성 " %a)
        recode = ('sangchul.kr.\t\t\tIN\tA\t%s\n' %a)
        dnszonefile.write(recode)
    print("A 레코드 : %s 개 추가" %len(recodelist))
dnszonefile.close()

 

참고URL

- https://docs.aws.amazon.com/ko_kr/general/latest/gr/aws-ip-ranges.html

- http://egloos.zum.com/entireboy/v/4767066

 

728x90
반응형