Batch or VBscript: ping servers/adress ouput the result into a .txt file

Hello experts,

I need a bat or a VB Script that do the following:

Ping: servers or adress defined as variable or in a .txt file.
Output the result into a result-ping.txt. this file should be generated at the same location of the script file.

Thank you in advance for your help.

Regards,
LVL 1
LD16Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Steve KnightIT ConsultancyCommented:
I have a number here I have already written if you want to take a look for starters... if you search the site for "PING" there are a number of different output formats already, e.g. just "OK" or "Bad" or the full PING output with response times etc.

http://scripts.dragon-it.co.uk/links/batch-monitor-ping-email
http://scripts.dragon-it.co.uk/links/batch-ping-check-hosts
http://scripts.dragon-it.co.uk/links/batch-ping-list-of-hosts-3

Steve
0
oBdACommented:
Try this:
@echo off
setlocal
set MachineFile=D:\Temp\test.txt
set ResultsFile=%~dp0result-ping.csv
if exist "%ResultsFile%" del "%ResultsFile%"
for /f "delims=" %%c in ('type "%MachineFile%"') do (
	echo Processing '%%~c' ...
	ping.exe -4 %%c | find /i "TTL" >NUL
	if errorlevel 1 (
		>>"%ResultsFile%" echo "%Date%","%Time%","%%~c","Not responding"
	) else (
		>>"%ResultsFile%" echo "%Date%","%Time%","%%~c","OK"
	)
)

Open in new window

0
David Paris VicenteSystems and Comunications  Administrator Commented:
Despite of the above examples I prefer using powershell.
You can copy the code to a PS1 file and is ready to use.
$Date = get-date
$logs = "C:\Users\UseraccoutnName\Documents\"
$PingOKfile = "$Logs\ping_ok.txt"
$NoPingfile = "$Logs\no_ping.txt"
$LogFile    = "$Logs\allping.log"


Out-File $PingOKfile   # reset file to empty
Out-File $NoPingfile   # reset file to empty
Out-File $LogFile      # reset file to empty
"Servers pingable"     | Out-File $PingOKfile -Append
"Servers not pingable" | Out-File $NoPingfile -Append

# Function Ping-Host
function Ping-Host
{
 $out #= $Null
 $results = gwmi -query "SELECT * FROM Win32_PingStatus WHERE Address = '$server'"
	if ($results.StatusCode -eq 0)
	{
	$out = "$server is reachable  --- $Date" 
		Write-Host $out -BackgroundColor darkgreen
		Write-Output $out
		$out | Out-File $PingOKfile -Append
	}
	else
	{
	$out = "$server is not reachable --- $Date"
		Write-Host $out -ForegroundColor yellow -BackgroundColor red
		Write-Output $out
		$out | Out-File $NoPingfile -Append
		
	}
}
#Grab the Servers or Workstations from a file
$computers = Get-Content "C:\Users\dv88006\Documents\allservers-toPing.txt"

$servers = $computers
# Read text file ping the machines
Foreach ($server in $servers) {
if ($server.length -gt 3) {
	$myCol = @()
	$myCol = Ping-Host
	$server |  Out-File $LogFile -Append
	}
}

Open in new window


I hope it helps,

D.
0
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

LD16Author Commented:
Hello experts,

Thank you for your help.
I just need to ouput the statistics of the ping.
Thank you again for your help.
0
Steve KnightIT ConsultancyCommented:
David - Added to my useful scripts here to have a play with... Don't do a huge amount of PS, frankly some of my customers VBScript is modern let alone PS, some still have sadly Windows 2000 and NT Servers, I suppose I should be greatful they are NT4!

On old sites/kit and when I can't run other software I have other batch files to monitor specific ports using tcping.exe, normal PINGs and email like the one below, works nicely.

Steve

KeepPinging.cmd (runs in a loop)
@Echo off
setlocal enabledelayedexpansion
set pinglog=c:\scripts\pinglog.txt
set olddate=%date%

echo %date%,%time%,Log Started
echo %date%,%time%,Log Started >>%pinglog%
                               
:next

REM ping some hosts
set hhmm=%time:~0,2%%time:~3,2%

set fail=
Call :pingit 158.43.128.1, "PIPEX DNS"
call :pingit 82.153.x.x, "ECLIPSE"
call :pingit 192.168.x.x, "ROUTER IN"
call :pingit 82.152.x.x, "ROUTER OUT"

call :pingit 192.168.x.x, "SERVER1"

REM Skip check for Server2 when closed for backup 1-2am
if %hhmm% GEQ 100 IF %hhmm% LEQ 159 goto SkipServer2
  call :pingit 192.168.x.x, "SERVER2"
  call :tcpping 192.168.x.x, "SERVER2 NOTES", 1352
:skipServer2

call :tcpping x.x.x.x, "SUPPORT NOTES", 1352
call :tcpping x.x.x.x, "SUPPORT HTTP", 80
call :tcpping x.x.x.x, "SUPPORT HTTPS", 443
call :tcpping x.x.x.x, "SUPPORT RDP", 3389

REM Skip customer Z Notes server between 9pm and 10pm
if %hhmm% GEQ 2100 IF %hhmm% LEQ 2200 goto Skip21
  call :tcpping x.x.x.x, "CUSTOMER Z NOTES", 1352
:Skip21

REM Skip servers between 1:30am and 5am for backups
if %hhmm% GEQ 130 IF %hhmm% LEQ 500 goto Skip45
  call :tcpping x.x.x.x "SERVER X SMTP", 25
  call :tcpping x.x.x.x "SERVER X HTTP", 80
  call :tcpping x.x.x.x "SERVER X IMAP", 143
:Skip45

REM The dot on the next line is Control G "BEL" which beeps... add is using EDIT from CMD prompt.
if "%fail%"=="1" (
  echo 
) ELSE (
REM  echo %date% %time% ALL OK
  SET /p =.<NUL
REM  echo %date%,%time%,ALL OK >> "%pinglog%"
)

REM Wait 5 mins
TITLE %date% %time% - waiting 300 seconds....
call :delay10 30

REM Check if is next day yet
if not %olddate%==%date% (
  set olddate=%date%
  echo.
  echo %date% %time% NEW DAY
  echo.
)

goto next

exit /b

:delay10
  ping 127.0.0.1 -w 10000 -n %~1 >NUL 2>&1
exit /b

:pingit
TITLE PING %~2 [%~1]
ping %1 -n 1 -w 1000 >NUL || (
  echo.
  echo %date%,%time%,FAIL,%1,%~2 >> %pinglog%
  echo %date% %time% FAIL %1 %~2
  set fail=1
)
exit /b

:tcpping
TITLE TCP PING %~2 [%~1:%~3]
tcping -n 2 -i 10 -w 800 -s %~1 %~3 | find "/tcp" > tcp.txt
find "open" < tcp.txt > NUL || (
  set fail=1
  echo.
  echo %date%,%time% FAIL %~1 %~2 %~3
  type tcp.txt 
  (echo %date%,%time%,FAIL,%1,%~2,%~3
  type tcp.txt )>> %pinglog%
)

exit /b

Open in new window


which combined with a VBScript to monitor those PING files using task scheduler to run periodically can let you know:

Const ForReading = 1, ForWriting = 2, ForAppending = 8

Const MailServer = "x.x.x.x" ' Mail Server to use for SMTP
Const MailServerPort = "25" ' SMTP Port used at Mail server (25 is default)
Const MailTo = "email@yourdomain.com" ' Who should be notified
Const MailFrom = "servername@yourdomain.com" 
subject = "Server packet / PING issue"

Body =""
on error resume next
REM Get body of message
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
  Set f = fso.OpenTextFile("c:\scripts\IssueLog.txt", ForReading)
    Body = f.ReadAll
  f.Close
Set f = Nothing
Set fso = Nothing

SendMail MailFrom , MailTo , subject , body, MailServer , MailServerPort 

Sub SendMail(Sender, Recipient, Subject, Message, Server, Port)
  Set objEmail = CreateObject("CDO.Message")
  objEmail.From = Sender
  objEmail.To = Recipient
  objEmail.Subject = Subject 
  objEmail.Textbody = Message
  objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
  objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = Server
  objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = Port
  objEmail.Configuration.Fields.Update()
  objEmail.Send
End Sub

Open in new window

0
Steve KnightIT ConsultancyCommented:
From your last response, try this then perhaps?
http://scripts.dragon-it.co.uk/links/batch-ping-list-of-hosts-3

Steve
0
LD16Author Commented:
Thank you. I tried before but I get an empty pingres.txt.
0
Steve KnightIT ConsultancyCommented:
Just tried it as it stands.  The "pingres.txt" is a temporary file it uses for the processing.  There is a logfile.txt with the output in, just ran it as on the website there and seems OK here.

Steve
0
oBdACommented:
Just for the fun of it, here's a version that uses WMI to ping. The script isn't language dependent, and the format of the output csv can easily be adjusted.
@echo off
setlocal enabledelayedexpansion
set MachineFile=D:\Temp\test.txt
set ResultsFile=D:\Temp\test.csv
set Count=4
set Buffersize=32
set Timeout=4000

call :PingStatusCode_Init
>"%ResultsFile%" echo "Host","Address","Bytes","Sent","Received","Lost","%% Loss","Min","Max","Average","Status"
for /f %%a in ('type "%MachineFile%"') do (
	<NUL set /p Dummy=Sending %Count% pings to %%a ...
	call :ping /Host:%%a /Count:%Count% /Timeout:%Timeout% /Buffersize:%BufferSize%
	>>"%ResultsFile%" echo "%%a","!PKT_Address!","!Buffersize!","!PKT_Sent!","!PKT_Received!","!PKT_Lost!","!PKT_Loss!","!RT_Min!","!RT_Max!","!RT_Average!","!Status!"
	echo  !Status!
	echo 	Host = %%a, Address = !PKT_Address!, Bytes = !Buffersize!
	echo 	Sent = !PKT_Sent!, Received = !PKT_Received!, Lost = !PKT_Lost! ^(!PKT_Loss!%%^)
	echo 	Minimum = !RT_Min! ms, Max = !RT_Max! ms, Average = !RT_Average! ms
)
goto :eof

:ping {/Host:<Host>} [/Count:<Count>] [/Timeout:<Timeout>] [/Buffersize:<BufferSize>]
REM Win32_PingStatus class, https://msdn.microsoft.com/en-us/library/aa394350(v=vs.85).aspx
set args[Buffersize]=32
set args[Count]=4
set args[Timeout]=1000
:GetArguments
	if "%~1"=="" goto ArgumentsEnd
	for /f "tokens=1* delims=/:" %%a in ("%~1") do set args[%%a]=%%b
	shift
goto GetArguments
:ArgumentsEnd
set /a RT_Min = 2147483647
set /a RT_Max = 0
set /a RT_Average = 0
set PKT_Address=n/a
set /a PKT_Sent = 0
set /a PKT_Received = 0
set /a PKT_Lost = 0
for /l %%i in (1, 1, %Count%) do (
	for /f "delims=" %%a in ('wmic.exe Path Win32_PingStatus WHERE "Address='%args[Host]%' AND BufferSize=%args[Buffersize]% AND Timeout=%args[Timeout]%" get Address^, Buffersize^, ProtocolAddress^, ReplySize^, ResponseTime^, ResponseTimeToLive^, StatusCode /format:list ^| find.exe "="') do (
		for /f "tokens=1* delims==" %%b in ("%%a") do (set PS_%%b=%%c)
	)
	if "!PS_StatusCode!"=="" goto EndPing
	set /a PKT_Sent += 1
	if "!PS_StatusCode!"=="0" (
		set PKT_Address=!PS_ProtocolAddress!
		set /a PKT_Received += 1
		if !PS_ResponseTime! lss !RT_Min! (set RT_Min=!PS_ResponseTime!)
		if !PS_ResponseTime! gtr !RT_Max! (set RT_Max=!PS_ResponseTime!)
		set /a RT_Average += PS_ResponseTime
	) else (
		set /a PKT_Lost += 1
	)
	if %Count% gtr 1 (ping.exe localhost -4 -n 2) >NUL
)
:EndPing
if "%PKT_Address%"=="n/a" (
	set RT_Min=-
	set RT_Max=-
	set RT_Average=-
) else (
	set /a RT_Average /= PKT_Sent
)
set /a PKT_Loss = ^(PKT_Lost * 100^) / Count
set Status=!StatusCode[%PS_StatusCode%]!
goto :eof

:PingStatusCode_Init
set StatusCode[]=Could not find host
set StatusCode[0]=Success
set StatusCode[11001]=Buffer Too Small
set StatusCode[11002]=Destination Net Unreachable
set StatusCode[11003]=Destination Host Unreachable
set StatusCode[11004]=Destination Protocol Unreachable
set StatusCode[11005]=Destination Port Unreachable
set StatusCode[11006]=No Resources
set StatusCode[11007]=Bad Option
set StatusCode[11008]=Hardware Error
set StatusCode[11009]=Packet Too Big
set StatusCode[11010]=Request Timed Out
set StatusCode[11011]=Bad Request
set StatusCode[11012]=Bad Route
set StatusCode[11013]=TimeToLive Expired Transit
set StatusCode[11014]=TimeToLive Expired Reassembly
set StatusCode[11015]=Parameter Problem
set StatusCode[11016]=Source Quench
set StatusCode[11017]=Option Too Big
set StatusCode[11018]=Bad Destination
set StatusCode[11032]=Negotiating IPSEC
set StatusCode[11050]=General Failure
goto :eof

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Batch

From novice to tech pro — start learning today.