[python] 운영체제별 어댑터 자동 감지로 가장 빠른 DNS 서버 설정하기

Yoo·2025년 7월 30일

목표: 사용자의 어댑터를 자동으로 감지하여 운영체제별 가장 빠른 DNS 서버로 설정하기(win, mac)

import platform, subprocess

라이브러리 추가

platform

  • 정의
    운영체제(OS) 관련 정보를 가져올 수 있게 해주는 모듈
  • 용도
    OS 이름, 버전, 구조 등

subprocess

  • 정의
    터미널 명령어 및 외부 명령을 실행할 수 있게 해주는 모듈
  • 용도
    CLI 명령 실행

운영체제 확인

def set_dns(dns_ip : str): # DNS 설정
    os_name = platform.system() 

dns_ip : 가장 빠른 DNS 서버 ip를 받음(문자열)
platform.system() : 사용자의 운영체제 이름을 문자열로 반환


① Win

네트워크 어댑터 상태 확인

def detect_adapter_win():
    result = subprocess.run(
        'netsh interface show interface',
        shell= True, capture_output= True, text= True, encoding= 'utf-8'
    )

subproces.run : 외부(터미널) 명령어를 실행하는 함수
netsh interface show interface : 네트워크 어댑터 상태를 보여주는 명령어

shell=True : 문자열로 명령을 해석해서 실행하도록 지정
capture_output=True : 명령어의 결과를 파이썬 코드에서 변수로 받아옴
text=True : 출력 결과를 바이트에서 문자열로 바꿔줌

결과를 리스트로 저장

lines = result.stdout.splitlines()

result.stdout : subprocess.run()에서 실행한 문자열 결과
1) result = 전체 결과 객체 (여러 속성을 담고 있음)
2) result.stdout = 명령어 실행 결과 (실제 화면에 나오는 텍스트)
3) result.stderr = 에러 메시지 (오류 메시지)
splitlines() : 줄바꿈 문자를 기준으로 분리해서 리스트로 만들어주는 함수


저는 현재 이더넷을 사용중입니다.

어댑터 이름 추출

for line in lines:
        if "Connected" in line or "연결됨" in line:
            return line.strip().split()[-1]
        raise Exception("Windows 어댑터 이름을 찾을 수 없습니다.")

line.strip() : 양쪽 공백 제거
' 연결됨 전용 Wi-Fi ' → '연결됨 전용 Wi-Fi']
split() : 공백 기준으로 문자열을 나눠 리스트로 만듬
'연결됨 전용 Wi-Fi' → ['연결됨', '전용', 'Wi-Fi']
[-1] : 마지막 인덱스(어댑터 이름)

DNS 설정

if(os_name == "Windows"):
        adapter = detect_adapter_win()
        command = f'netsh interface ip set dns name="{adapter}" static {dns_ip}'

DNS 리셋

if(os_name == "Windows"):
        adapter = detect_adapter_win
        command = f'netsh interface ip set dns name= "{adapter}" dhcp'

dhcp : 동적 호스트 설정 프로토콜, 자동으로 네트워크 장치 정보를 설정


② Mac

def detect_adapter_mac():
    result = subprocess.run(
        'networksetup -listallnetworkservices',
        shell = True, capture_output= True, text= True, encoding='utf-8'
    )
    lines = result.stdout.splitlines()

    for line in lines:
        if line and not line.startswith("*"):
            return line.strip()
        raise Exception("Mac 어댑터 이름을 찾을 수 없습니다.")

networksetup -listallnetworkservices : 네트워크 어댑터 전체 목록 출력

DNS 설정

elif(os_name == "Darwin"):
        adapter = detect_adapter_mac()
        command = f'networksetup -setdnsservers "{adapter}" {dns_ip}'

DNS 리셋

elif(os_name == "Darwin"):
        adapter = detect_adapter_mac
        command = f'networksetup -setdnssservers "{adapter}" Empty'

DNS 설정 변경 적용

result = subprocess.run(command, shell=True,
capture_output=True, text=True, encoding="utf-8")

오류 시 메시지 출력

if(result.returncode != 0):
        raise Exception(f"DNS 설정 실패 {result.stderr.strip()}")

코드

import platform, subprocess

def detect_adapter_win(): # Win 어댑터 탐지
    result = subprocess.run(
        'netsh interface show interface',
        shell = True, capture_output= True, text= True, encoding='utf-8'
    )
    lines = result.stdout.splitlines()

    for line in lines:
        if "Connected" in line or "연결됨" in line:
            return line.strip().split()[-1]
        raise Exception("Windows 어댑터 이름을 찾을 수 없습니다.")
    
def detect_adapter_mac(): # mac 어댑터 탐지
    result = subprocess.run(
        'networksetup -listallnetworkservices',
        shell = True, capture_output= True, text= True, encoding='utf-8'
    )
    lines = result.stdout.splitlines()

    for line in lines:
        if line and not line.startswith("*"):
            return line.strip()
        raise Exception("Mac 어댑터 이름을 찾을 수 없습니다.")

def set_dns(dns_ip : str): # DNS 설정
    os_name = platform.system() 
    if(os_name == "Windows"):
        adapter = detect_adapter_win()
        command = f'netsh interface ip set dns name="{adapter}" static {dns_ip}'
    elif(os_name == "Darwin"):
        adapter = detect_adapter_mac()
        command = f'networksetup -setdnsservers "{adapter}" {dns_ip}'
    else:
        raise Exception("Windows, Mac만 지원합니다.")
    
    result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding="utf-8")

    if(result.returncode != 0):
        raise Exception(f"DNS 설정 실패 {result.stderr.strip()}")

def reset_dns():
    os_name = platform.system()
    if(os_name == "Windows"):
        adapter = detect_adapter_win
        command = f'netsh interface ip set dns name= "{adapter}" dhcp'
    elif(os_name == "Darwin"):
        adapter = detect_adapter_mac
        command = f'networksetup -setdnssservers "{adapter}" Empty'
    else:
        raise Exception("Windows, Mac만 지원합니다.")
    
    result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding="utf-8")
profile
월1억벌기

0개의 댓글