Check if Ping fails to connect and write to log - windows

I have written a batch script that connects to network drives and copies files using a list of IPs in a text document - the script is as below.
TITLE Upgrading Contactless Price Limit
ECHO starting >> UpgradeLog.log
#ECHO on
rem CLS
echo Collect IP Address List
SET ListIP=C:\PMC\30To45Upgrade\tills.txt
echo Sets the folder we will use
SET PMC=C:\PMC\30To45Upgrade\VX820_cont45_Config\
ECHO Begin Mapping and Copying
ECHO.
echo Starts a FOR loop using the selected IP list
FOR /F %%a IN (%ListIP%) DO (
echo This will attempt to log into the C$ share of the target PC.
net use \\%%a\c$ /u:username password >NUL >> UpgradeLog.log
ECHO.
ECHO Copying directory to: %%a... >> UpgradeLog.log
ECHO.
echo Uses the Robocopy command to send the folder to the specified Till
mkdir \\%%a\c$\retailjava\icc\VX820_cont45_Config
C:\robocopy.exe %PMC% \\%%a\c$\retailjava\icc\VX820_cont45_Config /e /r:0 /w:10 /v /z >> UpgradeLog.log
ECHO.
ECHO Disconnecting from %%a... >> UpgradeLog.log
ECHO.
echo Disconnected from the share.
net use \\%%a\c$ /DELETE>NUL >> UpgradeLog.log)
ECHO. >> UpgradeLog.log
pause
However if the IP is offline it takes a long time to fail and move on to the next - I think the best solution if to ping the IP address first and if it does not respond move on to next
So a block of code like this
FOR /F %%a IN (%ListIP%) DO (
ping %%a >> Failed.log
)
However this block would write if it connected or not and I just want the failed pings - so not sure how to do this.
Also if I enter this in my code like this - even if it fails it carries on to the robocopy so it needs some sort of if/else statement as far as I can tell but not sure how to implement this. Any help?
Attempted Fix
TITLE Upgrading Contactless Price Limit
ECHO starting >> UpgradeLog.log
#ECHO on
rem CLS
echo Collect IP Address List
SET ListIP=C:\PMC\30To45Upgrade\tills.txt
echo Sets the folder we will use
SET PMC=C:\PMC\30To45Upgrade\VX820_cont45_Config\
ECHO Begin Mapping and Copying
ECHO.
echo Starts a FOR loop using the selected IP list
FOR /F %%a IN (%ListIP%) DO (
ping %%a | find "TTL=" && (
echo This will attempt to log into the C$ share of the target PC.
net use \\%%a\c$ /u:username password >NUL >> UpgradeLog.log
ECHO.
ECHO Copying directory to: %%a... >> UpgradeLog.log
ECHO.
echo Uses the Robocopy command to send the folder to the specified Till
mkdir \\%%a\c$\retailjava\icc\VX820_cont45_Config
C:\robocopy.exe %PMC% \\%%a\c$\retailjava\icc\VX820_cont45_Config /e /r:2 /w:10 /v /z >> UpgradeLog.log
ECHO.
ECHO Disconnecting from %%a... >> UpgradeLog.log
ECHO.
echo Disconnected from the share.
net use \\%%a\c$ /DELETE>NUL >> UpgradeLog.log
) || (
echo %%a Failed to connect >> failed.log
)
)
ECHO. >> UpgradeLog.log
pause

FOR /F %%a IN (%ListIP%) DO (
ping %%a | find "TTL=" && (
echo %%a is reachable
rem insert your payload here
) || (
echo %%a is not available
)
)
where && acts as "if previous command (find) was successful then" and || acts as "if previous command (find) failed then" (acts as "else" here)

Related

Pinging to multiple servers via windows batch script

I'm trying to check response from list of n-thousand IPs using ping command via windows batch script and save all results in a file (yes if response and no if don't). Is this even possible via batch script? When I'm using script printed below (pingingN.bat) I'm getting only first IP answer.
#ECHO OFF
SET ServerList="C:\MyPath\ip.txt"
SET LogFile="C:\MyPath\PingResults.txt"
IF EXISTS %LogFile% DEL %LogFile%
FOR %%a IN (%ServerList%) DO (
ping -n 1 %%a | find "TTL=" > NUL
IF %ERRORLEVEL% NEQ 0 (
echo no >> %LogFile%
) ELSE (
echo yes >> %LogFile%
)
)
Based on my comment and using the && and || conditionals, here's how I would do it:
#Echo Off
Set "ServerList=C:\MyPath\ip.txt"
Set "LogFile=C:\MyPath\PingResults.txt"
If Not Exist "%ServerList%" Exit /B
>"%LogFile%" (For /F UseBackQ %%A In ("%ServerList%"
) Do Ping -n 1 %%A|Find "TTL=">Nul&&(Echo Yes [%%A])||Echo No [%%A])
You'll note that I have also included the IP in the output, otherwise your log file will not show you which ones did or didn't pass/fail.
you can use delayed Expansion or if errorlevel (as commented by aschipfl) or use another approach:
(FOR %%a IN (%ServerList%) DO (
ping -n 1 %%a | find "TTL=" > NUL && (
echo %%a, yes
) || (
echo %%a, no
)
)>%LogFile%
where && means "if previous command (find) was successful then" and || "if previous command (find) failed then"
Just redirecting once the whole output instead of each line on it's own gives you a big speed boost.
Create a file (test.txt) and list down all the IPs you want to ping.
Create another bat.file and write this command.
(for /F %i in (test.txt) do ping -n 1 %i 1>nul && echo %i UP || echo %i DOWN ) 1>result.txt
Run this command, It will list down which IP is up and which one is down.

Checking admin access for a particular file using batch file

I want to know whether my host file has access to EDIT or not using errorcode but i am always getting error code as 0..Please help me out in getting the code to check for a admin access for a particular specified file
I am using below code, but not working
#echo off
setlocal enabledelayedexpansion enableextensions
attrib -s -h -r %systemroot%\system32\drivers\etc\hosts
echo %errorlevel%
echo.
IF %errorlevel% NEQ 0 (
echo.
echo Do not have access..
pause >nul
exit
) else (
echo Has Access..
pause >nul
)
You need to check the file permission,there are many ways to achieve this one by reading the file and another getting file permission using cacls command..
*(for example)
#echo off
SETLOCAL EnableDelayedExpansion
findstr /c:"any string" %systemroot%\system32\drivers\etc\hosts
echo %errorlevel%
echo.
if errorlevel 1 (
echo.
echo File Required Administrator Access
pause >nul
exit
) else (
echo Administrator Access ..
pause >nul
)

Windows Batch Check Hostname Exists

I want to check if a hostname exists on my PC (ie found in hosts file under C:\Windows\System32\drivers\etc).
Is there a way to find if it exist using a batch command or some other way?
Give a try for this batch file with some extra info :
#echo off
set "SearchString=localhost"
set "LogFile=%userprofile%\Desktop\LogFile.txt"
set "hostspath=%windir%\System32\drivers\etc\hosts"
(
Echo **************************** General info ****************************
Echo Running under: %username% on profile: %userprofile%
Echo Computer name: %computername%
Echo Operating System:
wmic os get caption | findstr /v /r /c:"^$" /c:"^Caption"
Echo Boot Mode:
wmic COMPUTERSYSTEM GET BootupState | find "boot"
Echo Antivirus software installed:
wmic /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get displayName | findstr /v /r /c:"^$" /c:"displayName"
Echo Executed on: %date% # %time%
Echo ********************* Hosts' File Contents with the string "%SearchString%" ************************
)>"%LogFile%"
for /f "delims=" %%a in ('Type "%hostspath%" ^| find /I "%SearchString%"') Do (
echo %%a >> "%LogFile%"
)
Start "" "%LogFile%"
Easier and more robust solution
url.bat:
#echo off
set url=%1
ping -n 1 %url% > nul 2> nul
if "%errorlevel%"=="0" (
echo %url% exists
) else (
echo %url% does not exist
)
Test
> url.bat google.com
google.com exists
> url.bat google.commmmmm
google.commmmmm does not exist
What you possibly can do is pinging the hostname you are looking for and then check for certain strings, that will show you if the hostname could be found or not. Would look like this (I guess):
#echo off
setlocal EnableDelayedExpansion
set /p input= "Hostname"
set hostexists=yes
For /f "tokens=1,2" %%a in ('ping -n 1 !input!') do (
if "x%%a"=="xFOO" if "x%%b"=="xBAR" set hostexists=no
)
If "x!hostexists!"=="xno" (
echo. "Does not exist"
) ELSE (
echo. "Does exist"
Pause
Basic thought is that when you try to ping a hostname that is not available, you will get a specific output from the commandline. Try it yourself: Open the cmd.exe (Hit the Windows-Button +R and type cmd) and in the commandline write ping foobar and wait a bit. You should get a message like: Ping-Request could not find "foobar" [...]. You take the first two words and put them into the code: 1st word to FOO and 2nd to BAR.
The program will look into the output of the ping command and place the first two words (=tokens) in %%a and %%b checking if they are equal to the desired words, marking the host does not exist.
I hope this will help :) Not sure if that is what you wanted :D
Greetings
geisterfurz007

How to update %time% variable in Batch Script

I have a batch script for backing up databases. I echo the %time% that script starts and then the %time% it ends to a log file. Even though the script takes 5 minutes to backup our databases the end time is identical to the start time.
#echo off
:: Credentials preconfigured for backup-operator
net use y: \\172.16.104.201\Backups
:: Date in format YYYY.MM.DD
set DATESTAMP=%DATE:~-4%.%DATE:~3,2%.%DATE:~0,2%
set LOCAL_DIR=F:\Backups\
set EXTERN_DIR=Y:\DB3\
:: Output all to txt
>"%LOCAL_DIR%SQLBackups-%DATESTAMP%.txt" (
echo.
echo ------------------------------------------------------------------------------
echo -- Starting SQL Backups %date% %time% --
echo ------------------------------------------------------------------------------
echo.
:: Backup and Copy loop
setlocal enabledelayedexpansion
for %%i in (
DB1
DB2
DB3
DB4 etc...
) do (
set DATABASENAME=%%i
set BACKUPFILENAME=!LOCAL_DIR!!DATABASENAME!-!DATESTAMP!.bak
echo.
echo ------------------------------------------------------------------------------
echo -- Backing Up Database !DATABASENAME! to local--
echo ------------------------------------------------------------------------------
echo.
sqlcmd -E -S DB3 -d master -Q "BACKUP DATABASE [!DATABASENAME!] TO DISK = '!BACKUPFILENAME!' WITH DESCRIPTION = 'Full backup [!DATABASENAME!]', CHECKSUM, INIT, COMPRESSION"
echo.
echo.
echo -- Copying !DATABASENAME! Backup to external--
robocopy !LOCAL_DIR! !EXTERN_DIR! !DATABASENAME!-!DATESTAMP!.bak
echo.
echo -- !DATABASENAME! End --
echo.
echo.
)
endlocal
:: Delete files older than -d days from local
forfiles -p %LOCAL_DIR% -s -m *.bak -d "-180" /C "cmd /c echo #path & del #path""
forfiles -p %LOCAL_DIR% -s -m *.txt -d "-180" /C "cmd /c echo #path & del #path""
echo.
echo.
echo -- Script Complete %date% %time% --
echo.
)
robocopy %LOCAL_DIR% %EXTERN_DIR% "SQLBackups-%DATESTAMP%.txt"
net use y: /delete
You have to add Setlocal EnableDelayedExpansion below #echo off and access the time with !time! instead of %time%. That should be it.
Volatile variables are unreliable. Any program, user, or install can kill them. Use tried and true methods.
for /f "Delims=" %A in ('time /t') do Set MyTime=%A
For a way that will work on all computers.

How to call Windows gethostbyaddr API using BATCH script

I already have a small script in perl to do reverse lookup, but it is not portable unless the other machine also has perl installed. I want a script that can run on colleagues machines seamlessly and also can be converted into a custom command (by updating PATH & PATHEXT environment variables). The script file must be portable and available to non admin users.
Batch script seems to fit this purpose, but I cannot figure out how to call the gethostbyaddr API. I suppose VBScript is also an option and open to that.
gethostbyaddr API
Here's two batch scripts. Hopefully at least one can help.
#ECHO OFF
::Lookup.bat
::http://www.computing.net/answers/programming/ip-by-hostname/25313.html
::Takes input file of hostnames and creates csv file with hostnames and IP addresses.
::Gets IP's using nslookup
:: Output in file hostnames.csv in current folder
if "%1"=="" goto :Syntax
SET SCRIPTPATH=%~p0
CD %SCRIPTPATH%
del hostnames.csv
for /f %%e in (%1) do call :LOOKUP %%e
echo Done!!!
goto :EOF
:LOOKUP
SET HOST1=%1
FOR /F "skip=4 tokens=2 delims=:" %%A IN ('2^>NUL nslookup %1') DO ( ECHO %1,%%A>>%SCRIPTPATH%hostnames.csv )
GOTO :EOF
:Syntax
echo.
echo Syntax:
echo.
echo %0 ^<FileName^>
echo.
echo where ^<FileName^> is a file containing a list of hostnames.
echo.
echo The batch file will return the results to file hostnames.csv in current folder
goto :EOF
#echo off
::gethostname.bat
::Takes input file of IP addresses and creates csv file with IP address and hostnames.
::Gets hostnames using netBIOS, which is usually accurate. If no info avail from
::netBIOS, then use nslookup. Plenty of debug statements in screen output. :)
:: Output in file C:\TEMP\ip-resolved.csv
if "%1"=="" goto :Syntax
SET SCRIPTPATH=%~p0
CD %SCRIPTPATH%
echo ip,hostname,power>C:\TEMP\ip-resolved.csv
for /f %%e in (%1) do call :PING-NBT %%e
echo Done!!!
goto :EOF
:PING-NBT
set ipaddress=%1
set host1=
echo.
echo ***Pinging %ipaddress%
SET ON=0
PING -n 1 %1 | find /i "Reply from" >nul && SET ON=1
echo Just parsed ping reply... host is %ON%
REM Next line skips netBIOS check if host is offline
IF "%ON%"=="0" GOTO :LOOKUP %ipaddress% %ON%
echo Proceeding to nbtstat with host %on%
REM The next lines check netBIOS name.
echo nbt1-start
for /f %%i in ('nbtstat -a %1^|find "<20>"') do #set host1=%%i
echo nbt=%host1% power=%ON%
REM If there isn't a NetBIOS name, then skips to nslookup section.
REM echo %2
if "%host1%"=="" goto :LOOKUP %1 %ON%
ECHO %ipaddress%,%host1%,%ON% >> C:\TEMP\ip-resolved.csv
echo nbt2-end
goto :EOF
:LOOKUP
echo nslookup1-start
for /f "tokens=2" %%i in ('nslookup %1^|find "Name:"') do #set host1=%%i
echo nslookup=%host1% power=%2
REM Next line=if host var
rem if not "%host1%"=="%1" goto :EOF
ECHO %ipaddress%,%host1%,%2 >>C:\TEMP\ip-resolved.csv
set host1=
echo nslookup2-end
goto :EOF
:Syntax
echo.
echo Syntax:
echo.
echo %0 ^<FileName^>
echo.
echo where ^<FileName^> is a file containing a list of IP addresses to
echo which we need the hostname.
echo.
echo The batch file will return the results via a file
echo C:\TEMP\ip-resolved.csv
goto :EOF

Resources