도메인 주소 뽑아내기

업무중 요청이 들어가는 도메인 IP 가 비주기적으로 변경이 이뤄진다 하여…

  1. 도메인 IP 가져오기
    1. 기본적인 nslookup 명령어
    2. 원하는 행과 값만 출력
    3. 한줄루 출력과 구분자 추가
    4. 파이썬으로 여러 도메인 관리
  2. 사용한 명령어
    1. Shell
      1. sed
      2. awk
      3. xargs
    2. Python
      1. os.system
      2. os.popen

도메인 IP 가져오기

업무중 요청이 들어가는 도메인 IP 가 비주기적으로 변경이 이뤄진다 하여 스크립트를 짜놔서 알아서 가공 하여 가져오게끔 할려합니다.

기본적인 nslookup 명령어

$ nslookup naver.com
# result
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
Name:   naver.com
Address: 223.130.195.95 <--
Name:   naver.com
Address: 223.130.195.200 <--
Name:   naver.com
Address: 223.130.200.107 <--
Name:   naver.com
Address: 223.130.200.104 <--

기본적으로 nslookup으로 도메인 출력입니다. 저희에게 필요한것은 Address: 223.130.195.95에 나오는 IPv4만 나오면 되어 저 부분만 출력 하도록 할 것입니다.

원하는 행과 값만 출력

$ nslookup naver.com |sed -n '3,$p' | grep Address | awk '{ print $2 }'
# result
# 223.130.200.104
# 223.130.195.95
# 223.130.200.107
# 223.130.195.200

이게 위 출력을 한줄로 출력을하며 구분자로 쉼표를 사용할 것입니다.

한줄루 출력과 구분자 추가

$ nslookup naver.com | sed -n '3,$p'  |  grep "Address" |  awk '25 > length  { print $2"/32"
 }' | xargs echo | sed 's/ /,/g'

 # result
 # 223.130.200.107/32,223.130.195.95/32,223.130.200.104/32,223.130.195.200/32

이렇게 해서 완성! 인줄 알았으니 관리하는 도메이니 한 두개가 아니라 여러개 여서 여기서 부터는 좀 더 간단하게 사용하기 위해 파이썬의 도움을 받기로 했습니다.

파이썬으로 여러 도메인 관리

import os

list = ['naver.com','google.com', 'twitter.com','daum.net', 'velog.io', 'facebook.com', 'instagram.com']
result = []
for i in list :
    splitString = os.popen("nslookup "+i+" | sed -n '3,$p'  |  grep \"Address\" |  awk '25 > length  { print $2\"/32\" }' | xargs echo | sed 's/ /,/g'").read()
    for i in splitString.split(","):
        result.append(i.rstrip())

print(result)
# result
# ['223.130.195.95/32', '223.130.195.200/32', '223.130.200.107/32', '223.130.200.104/32', '142.250.66.78/32', '104.244.42.129/32', '104.244.42.193/32', '211.249.220.24/32', '121.53.105.193/32', '13.209.219.203/32', '52.78.220.56/32', '157.240.215.35/32', '157.240.215.174/32']

결과가 잘 나오네요.

사용한 명령어

위에서 사용한 명령어들에 대해 알아 보도록 하겠습니다.

Shell

sed

sed 게시글

awk

xargs

Python

os.system

os.popen