Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 12개 있습니다.)
개발 환경 구성: 1. batch 파일에서 실행한 exe에서 batch 실행 문맥의 환경 변수 설정
; https://www.sysnet.pe.kr/2/0/238

개발 환경 구성: 89. 배치(batch) 파일에서 또 다른 배치 파일을 동기 방식으로 실행 및 반환값 얻기
; https://www.sysnet.pe.kr/2/0/958

개발 환경 구성: 103. DOS batch - 동기 방식으로 원격 서비스 제어
; https://www.sysnet.pe.kr/2/0/989

개발 환경 구성: 144. 윈도우에서도 유닉스처럼 명령행으로 원격 접속하는 방법
; https://www.sysnet.pe.kr/2/0/1245

개발 환경 구성: 166. DOS - ping 결과에서 평균 응답 시간값 추출하기
; https://www.sysnet.pe.kr/2/0/1340

개발 환경 구성: 215. DOS batch - 하나의 .bat 파일에서 다중 .bat 파일을 (비동기로) 실행하는 방법
; https://www.sysnet.pe.kr/2/0/1629

개발 환경 구성: 242. 배치 파일에서 Thread.Sleep 효과를 주는 방법
; https://www.sysnet.pe.kr/2/0/1768

개발 환경 구성: 328. Visual Studio(devenv.exe)를 배치 파일(.bat)을 통해 실행하는 방법
; https://www.sysnet.pe.kr/2/0/11293

스크립트: 13. 윈도우 배치(Batch) 스크립트에서 날짜/시간 문자열을 구하는 방법
; https://www.sysnet.pe.kr/2/0/11742

스크립트: 16. cmd.exe의 for 문에서는 ERRORLEVEL이 설정되지 않는 문제
; https://www.sysnet.pe.kr/2/0/12039

스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13685

Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
; https://www.sysnet.pe.kr/2/0/13861




DOS - ping 결과에서 평균 응답 시간값 추출하기


가끔 ^^ DOS 배치 파일을 다룰 일이 있습니다. 이번에는 ping 실행 결과에서 시간값을 추출해야 하는 상황이 발생했는데요. 보통, ping의 결과가 다음과 같은데,

C:>ping 164.124.101.2

Pinging 164.124.101.2 with 32 bytes of data:
Reply from 164.124.101.2: bytes=32 time=7ms TTL=51
Reply from 164.124.101.2: bytes=32 time=8ms TTL=51
Reply from 164.124.101.2: bytes=32 time=9ms TTL=51
Reply from 164.124.101.2: bytes=32 time=8ms TTL=51

Ping statistics for 164.124.101.2:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 7ms, Maximum = 9ms, Average = 8ms

원하는 것은 마지막 "Average = 8ms"에서 "8"이라는 숫자값입니다. (물론, 100도 될 수 있겠지요.)

먼저 실행 결과를 변수에 담아야 합니다.

@ECHO OFF

FOR /F "tokens=*" %%i in ('ping -n 2 164.124.101.2') do SET TOOLOUTPUT=%%i 

위와 같이 하면 TOOLOUTPUT 변수에는 Ping 실행 결과의 마지막 라인에 해당하는 내용이 보존됩니다.

%TOOLOUTPUT% == "Minimum = 8ms, Maximum = 10ms, Average = 8ms"

토큰을 기준으로 분리를 하여 "8ms"라는 값을 다음과 같은 실행문으로 추출할 수 있습니다.

for /f "tokens=9 eol=," %%f in ("%TOOLOUTPUT%") do set avgText=%%f

참고로, 각 토큰별 문자열 매핑은 다음과 같습니다.

tokens = 1 : Minimum
tokens = 2 : =
tokens = 3 : 8ms
tokens = 4 : Maximum
tokens = 5 : =
tokens = 6 : 10ms
tokens = 7 : Average
tokens = 8 : =
tokens = 9 : 8ms

그럼, 이야기가 다 끝난 것 같군요. ^^ "8ms"라는 문자열 역시 "ms"라는 토큰으로 분리를 하면 되니까요.

for /f "tokens=1 delims=m" %%a in ("%avgText%") do set str=%%a

echo %str%

위의 마지막 문장에서 echo로 찍힌 값이 바로 대상 컴퓨터에 ping으로 실행한 경우 걸린 평균 응답 시간이 됩니다.

참고로, 위의 문제를 푸는데 다음의 글에서 많은 도움을 얻었습니다. ^^

DOS - String Manipulation
; http://www.dostips.com/DtTipsStringManipulation.php




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 1/18/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2012-09-06 12시20분
[ryujh] 저는 날짜/시각 추출하여 폴더 생성 후 간단한 백업에 유용하게 사용 중 입니다.

rem ----
rem 압축 7집
rem ----
set todaydate=%date:~0,4%%date:~5,2%%date:~8,2%
if %time:~0,2% lss 10 (set todaytime=0%time:~1,1%%time:~3,2%%time:~6,2%) else (set todaytime=%time:~0,2%%time:~3,2%%time:~6,2%)
rem "C:\Program Files\7-Zip\7z" a -tzip -mx9 %cmdlocation%\_압축함\%todaydate%_%todaytime%.zip %cmdlocation%\_일일백업\*_%todaydate%_*\
"C:\Program Files\7-Zip\7z" a -mx9 %cmdlocation%\_압축함\%todaydate%_%todaytime%.7z %cmdlocation%\_일일백업\*_%todaydate%_*\

참고하세요.
[guest]
2012-09-06 12시21분
[ryujh] 댓글 시각이 UTC 이네요.
[guest]
2012-09-06 12시53분
^^ 이상하게 DOS 명령어들은 한번 쓰고 나면 잊어버리게 되어 다음에는 또 찾아보게 됩니다. (덧글이 UTC인것은 몰랐습니다. 그런데... 왠지 멋있어 보여서 그냥 고치지 않을까 합니다. ^^)

------------------------------------

Ping all addresses in network, windows
; https://stackoverflow.com/questions/13713318/ping-all-addresses-in-network-windows

FOR /L %i IN (1,1,254) DO ping -n 1 192.168.100.%i | FIND /i "Reply">>c:\temp\ipaddresses.txt

------------------------------------

Ping C# 예제 코드
; https://www.sysnet.pe.kr/2/0/13531#ping_code
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12208정성태4/12/202015932Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015738스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018384오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015048스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015059스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017882오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021144개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018369오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018485VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016127오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019513오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018759VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015930오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018249.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020975오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017866개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019875개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021013개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015558오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021171개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202025989Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015516오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017379오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202017949오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202019886오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202017681오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...