목표: 사용자의 어댑터를 자동으로 감지하여 운영체제별 가장 빠른 DNS 서버로 설정하기(win, mac)
import platform, subprocess
platform
subprocess
def set_dns(dns_ip : str): # DNS 설정
os_name = platform.system()
dns_ip : 가장 빠른 DNS 서버 ip를 받음(문자열)
platform.system() : 사용자의 운영체제 이름을 문자열로 반환
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] : 마지막 인덱스(어댑터 이름)
if(os_name == "Windows"):
adapter = detect_adapter_win()
command = f'netsh interface ip set dns name="{adapter}" static {dns_ip}'
if(os_name == "Windows"):
adapter = detect_adapter_win
command = f'netsh interface ip set dns name= "{adapter}" dhcp'
dhcp : 동적 호스트 설정 프로토콜, 자동으로 네트워크 장치 정보를 설정
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 : 네트워크 어댑터 전체 목록 출력
elif(os_name == "Darwin"):
adapter = detect_adapter_mac()
command = f'networksetup -setdnsservers "{adapter}" {dns_ip}'
elif(os_name == "Darwin"):
adapter = detect_adapter_mac
command = f'networksetup -setdnssservers "{adapter}" Empty'
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")