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
정성태

... 121  122  123  124  [125]  126  127  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
10797정성태5/23/201521514VC++: 91. 자식 스레드에 자동 상속되는 TEB의 SubProcessTag 필드파일 다운로드1
10796정성태5/23/201532358오류 유형: 293. SQL Server Management Studio 실행 시 "Cannot find one or more components" 오류
10795정성태5/23/201530472오류 유형: 292. InstallUtil로 .NET 서비스 등록 시 오류 - Operation is not supported. (Exception from HRESULT: 0x80131515). [3]
10794정성태5/22/201525425개발 환경 구성: 267. (무료) 마이크로소프트 온라인 강좌 소개 - 네트워킹 기초 [1]
2925정성태5/14/201525041디버깅 기술: 73. PDB 기호 파일의 경로 구성 방식파일 다운로드1
2924정성태5/14/201528331VS.NET IDE: 100. 비주얼 스튜디오 원격 디버깅 시 'Unknown function' 콜스택이 나온다면?
2923정성태5/12/201587737기타: 52. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 [17]
2922정성태5/12/201524593오류 유형: 291. ssindex.cmd 실행 시 '...[tfs_collection_url]...' not found in srcsrv.ini 오류 발생
2921정성태5/9/201530942개발 환경 구성: 266. 인텔에서 구현한 최대 절전 모드 기능 - Intel® Rapid Start Technology
2920정성태5/9/201522011오류 유형: 290. 디스크 관리자의 파티션 축소 시, There is not enough space available on the disk(s) to complete this operation.
2919정성태5/9/201521907오류 유형: 289. Error: this template attempted to load component assembly 'NuGet.VisualStudio.Interop, ...'
2918정성태5/9/201540434Windows: 111. 복구(Recovery) 파티션 삭제하는 방법 [3]
2917정성태5/9/201530852오류 유형: 288. .NET Framework 4.6이 설치된 경우 "Intel® Rapid Storage Technology (Intel® RST) RAID Driver"가 설치 안 되는 문제 [5]
2916정성태5/9/201531957오류 유형: 287. 레지스트리 권한 오류 - Cannot edit [Registry key name]: Error writing the value's new contents.
2915정성태5/9/201531072개발 환경 구성: 265. TrustedInstaller 권한으로 프로그램 실행시키는 방법 [11]
2914정성태5/9/201528428DDK: 7. 정식 인증서가 있는 경우 Device Driver 서명하는 방법 [2]
2913정성태4/30/201526149.NET Framework: 511. Build 2015 행사에서 소개된 (맥/리눅스/윈도우 용 무료) Visual Studio Code 개발 도구 [8]
2912정성태4/29/201521895오류 유형: 286. VirtualBox에 Windows 8/2012 설치 시 "Error Code: 0x000000C4" 오류 발생
2911정성태4/29/201520493오류 유형: 285. Visual Studio 2015를 제거한 경우 Microsoft.VisualStudio.Web.PageInspector.Loader 어셈블리를 못 찾는 문제 [2]
2910정성태4/29/201524438오류 유형: 284. System.TypeLoadException: Could not load type 'System.Reflection.AssemblySignatureKeyAttribute' from assembly [1]
2909정성태4/29/201520563오류 유형: 283. WCF 연결 오류 - Expected record type 'PreambleAck'
2908정성태4/29/201528878오류 유형: 282. 원격에서 SQL 서버는 연결되지만, SQL Express는 연결되지 않는 경우
2907정성태4/29/201518887.NET Framework: 510. 제네릭(Generic) 인자에 대한 메타데이터 등록 확인
2906정성태4/28/201521477오류 유형: 281. DebugView로 인한 System.Diagnostics.Trace.WriteLine 멈춤(Hang) 현상
2905정성태4/27/201521900오류 유형: 280. HttpResponse.Headers.Add에서 "System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode." 예외 발생
2904정성태4/27/201527077DDK: 6. ZwTerminateProcess로 프로세스를 종료하는 Device Driver 프로그램 [2]파일 다운로드1
... 121  122  123  124  [125]  126  127  128  129  130  131  132  133  134  135  ...