본문 바로가기
투윤아빠의 올IT

시스템 포트체크 배치 스크립트 / 응답시간 포함 / PowerShell 활용 / port check script

by 별다방김샘 2023. 11. 22.
반응형

IT 환경에서 여러 대의 시스템을 관리하고, 이들 시스템 간의 통신을 원활히 유지하는 것은 매우 중요합니다. 특히, 각 시스템이 올바른 포트로 서비스에 접근 가능한지 확인하는 것은 시스템 관리자에게 필수적인 업무 중 하나입니다.

Windows 환경에서 작동하는 배치 파일을 사용하여 여러 시스템에 대한 포트 체크를 자동화하는 방법을 써 보겠습니다. 이 스크립트는 시스템 목록을 읽어 들여 PowerShell을 활용하여 각 시스템의 특정 포트에 연결 가능한지를 테스트하고, 응답 시간까지 측정하여 결과를 로깅합니다.

 

 

 

목차

  • 1. 설정 초기화
  • 2.시스템 목록 및 로그 파일 설정
  • 3.인코딩 설정
  • 4. 로그 파일 초기화
  • 5. 시스템 목록 파일 루프
  • 6. 시스템 정보 추출
  • 7. Powershell을 통한 포트 테스트 및 응답시간 측정
  • 8.결과를 로그파일에 기록
  • 9. 인코딩 재설정 및 완료 메시지 출력
  • 10. 전체 소스

     

     

     

    1. 설정 초기화

    @echo off
    setlocal enabledelayedexpansion

    @echo off: 이 명령은 화면에 명령 실행 내용을 표시하지 않도록 설정합니다.

    setlocal enabledelayedexpansion: 확장된 변수 지연 활성화를 통해 반복문 내에서 변수 값을 변경할 수 있도록 합니다.

     

     

     

    2. 시스템 목록 및 로그 파일 설정

    :: Set the list file for systems (업무명:host:port)
    set list_file=systems.txt
    
    :: Set the log file path and name
    set log_file=port_check_log.txt

    set list_file=systems.txt: 시스템 목록이 있는 파일의 경로를 systems.txt로 설정합니다.

    set log_file=port_check_log.txt: 결과를 기록할 로그 파일의 경로와 이름을 port_check_log.txt로 설정합니다.

     

     

     

     

    3. 인코딩 설정

    :: Set the code page to UTF-8
    chcp 65001 > nul

    chcp 65001 > nul: 코드 페이지를 UTF-8로 설정합니다.

     

     

     

     

    4. 로그 파일 초기화

    echo Checking ports on multiple systems...
    
    :: Create an empty UTF-8 log file
    type nul > "%log_file%"

    echo Checking ports on multiple systems...: 포트를 확인하는 메시지를 출력합니다.

    type nul > "%log_file%": 빈 UTF-8 로그 파일을 생성합니다.

     

     

     

     

    5. 시스템 목록 파일 루프

    :: Loop through each line in the list file
    for /f "tokens=*" %%s in (%list_file%) do (

    echo Checking ports on multiple systems...: 포트를 확인하는 메시지를 출력합니다.

    type nul > "%log_file%": 빈 UTF-8 로그 파일을 생성합니다.

     

     

     

     

    6. 시스템 정보 추출

     set system=%%s
        for /f "tokens=1,2,3 delims=:" %%a in ("!system!") do (
            set task=%%a
            set host=%%b
            set port=%%c
            echo Task: !task!
            echo Host: !host!
            echo Port: !port!

    시스템 정보(업무명, 호스트, 포트)를 추출하고 각 변수에 할당합니다.

    echo Task: !task!, echo Host: !host!, echo Port: !port!: 현재 작업 중인 시스템의 정보를 출력합니다.

     

     

     

     

    7. Powershell을 통한 포트 테스트 및 응답시간 측정

          :: Use PowerShell to test the port and measure response time
            for /f "tokens=*" %%i in ('powershell -command "$stopwatch = [System.Diagnostics.Stopwatch]::StartNew(); $result = Test-NetConnection -ComputerName !host! -Port !port!; $stopwatch.Stop(); $response_time_ms = $stopwatch.Elapsed.TotalMilliseconds; $response_time_sec = [math]::Round($response_time_ms / 1000, 2); if ($result.TcpTestSucceeded -eq $true) { $result = 'Result: True' } else { $result = 'Result: False' }; 'Response Time: ' + $response_time_sec + ' sec', $result"') do (
                set "result_line=%%i"
            )

    PowerShell을 사용하여 현재 시스템의 지정된 포트에 대한 테스트를 수행하고 응답 시간을 측정합니다.

    결과를 result_line 변수에 저장합니다.

     

     

     

     

    8.결과를 로그파일에 기록

           :: Log the result to the specified log file with the task information
            echo Task: !task!, Host: !host!, Port: !port! - !result_line! >> "%log_file%"
        )
    )

    시스템 정보와 테스트 결과를 로그 파일에 기록합니다.

     

     

     

     

     

    9. 인코딩 재설정 및 완료 메시지 출력

    :: Reset the code page to the default
    chcp 437 > nul
    
    :: Display a completion message
    echo Check completed. Results are saved in "%log_file%"
    
    endlocal

    인코딩을 기본 값으로 재설정합니다.

    작업 완료 메시지를 출력합니다.

     

     

     

     

     

     

     

    10. 전체 소스

    @echo off
    setlocal enabledelayedexpansion
    
    :: Set the list file for systems (업무명:host:port)
    set list_file=systems.txt
    
    :: Set the log file path and name
    set log_file=port_check_log.txt
    
    :: Set the code page to UTF-8
    chcp 65001 > nul
    
    echo Checking ports on multiple systems...
    
    :: Create an empty UTF-8 log file
    type nul > "%log_file%"
    
    :: Loop through each line in the list file
    for /f "tokens=*" %%s in (%list_file%) do (
        set system=%%s
        for /f "tokens=1,2,3 delims=:" %%a in ("!system!") do (
            set task=%%a
            set host=%%b
            set port=%%c
            echo Task: !task!
            echo Host: !host!
            echo Port: !port!
    
            :: Use PowerShell to test the port and measure response time
            for /f "tokens=*" %%i in ('powershell -command "$stopwatch = [System.Diagnostics.Stopwatch]::StartNew(); $result = Test-NetConnection -ComputerName !host! -Port !port!; $stopwatch.Stop(); $response_time_ms = $stopwatch.Elapsed.TotalMilliseconds; $response_time_sec = [math]::Round($response_time_ms / 1000, 2); if ($result.TcpTestSucceeded -eq $true) { $result = 'Result: True' } else { $result = 'Result: False' }; 'Response Time: ' + $response_time_sec + ' sec', $result"') do (
                set "result_line=%%i"
            )
    
            :: Log the result to the specified log file with the task information
            echo Task: !task!, Host: !host!, Port: !port! - !result_line! >> "%log_file%"
        )
    )
    
    :: Reset the code page to the default
    chcp 437 > nul
    
    :: Display a completion message
    echo Check completed. Results are saved in "%log_file%"
    
    endlocal

     

     

     

    이 스크립트는 주어진 시스템 목록 파일(systems.txt)에 나열된 각 시스템에 대해 PowerShell을 사용하여 지정된 포트에 연결 가능한지를 테스트하고 응답 시간을 측정한 후 결과를 로그 파일(port_check_log.txt)에 기록합니다. 최종적으로는 인코딩을 기본 값으로 재설정하고 작업 완료 메시지를 출력합니다.

     

     

     

    반응형