Windows Batch Check Hostname Exists - windows

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

Related

Reporting Computer descriptions or not using WMIC

I am making a script detect for presence of certain programs on a list of PC's and then report back the hostname, software list and the description for easier locating.
Everything is fine but I'm having trouble tidying up the output when "no" description is found. Where as before I would get the info needed in a tidy list, when there is no description, it just reports ECHO is on. 'or' ECHO is off.
here is my code
title Problem Software Itinary
echo.
echo List of PC Names goes here Plugins\hostnames.txt
echo.
echo Press a key to start...
pause>nul
CLS
echo.
break>Plugins\Logs\Results.txt
for /f "usebackq tokens=*" %%A in (Plugins\hostnames.txt) do (
echo ============================================= & echo =============================================>>Plugins\Logs\Results.txt
echo Scanning PC %%A... 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
if exist "\\%%A\C$\FOO" echo FOO PROG Installed 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
if exist "\\%%A\C$\FOO2" echo FOO 2 PROG Installed 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
for /f "tokens=2 Delims==" %%B in ('WMIC /NODE:"%%A" os get description /VALUE ^| find "Description"') Do Echo %%B 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
echo ============================================= & echo =============================================>>Plugins\Logs\Results.txt
)
start "" Plugins\Logs\Results.txt
echo.
echo Done! Press any key to return to Menu...
pause>nul
goto :audit
Here is example of it working and the echo problem:-
=============================================
=============================================
Scanning PC TESTPC1...
FOO PROG Installed
GP-B82047-ROOM 4
=============================================
=============================================
Scanning PC TESTPC2...
FOO 2 PROG Installed
ECHO is on.
=============================================
=============================================
I would prefer to have something echo back like "No Description Found"
to cure it I have tried setting a desc variable to %%B (set desc=%%b) (in the wmic line) (instead of Do Echo %%B) and then if defined desc (echo desc) ELSE (echo no description available). However that doesnt work either, same issue. Also I tried with delayed expansions enabled and no luck there.
What am I missing - thanks !!?
You actually have part of the solution in your script already, or at least one possible solution:
for /f "tokens=2 Delims==" %%B in ('WMIC /NODE:"%%A" os get description /VALUE ^| find "Description"') Do Echo %%B 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
If this echo could be empty, just change it to
for /f "tokens=2 Delims==" %%B in ('WMIC /NODE:"%%A" os get description /VALUE ^| find "Description"') Do Echo.%%B 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
Note the . after the echo. That'll suppress the error message from echo.
Also, note, it's generally better to use some character other than . for this, since if you have the misfortune of running on a machine with a program named echo in the path, the results can be unpredictable. : works well for this, so:
for /f "tokens=2 Delims==" %%B in ('WMIC /NODE:"%%A" os get description /VALUE ^| find "Description"') Do Echo:%%B 2>&1 | Plugins\tee -a Plugins\Logs\Results.txt
Will accomplish the same goal.

Check if Ping fails to connect and write to log

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)

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.

Batch ping a list of computer names and write the results to file

The code below will write the computer name and ip address to file, but I would like it to also write the name of the computers it cannot ping with a fail next to it. I have no idea how I would modify the batch file to do this.
#echo off
Echo Pinging list...
set ComputerList=list.txt
Echo Computername,IP Address>Final.csv
setlocal enabledelayedexpansion
for /f "usebackq tokens=*" %%A in ("%ComputerList%") do (
for /f "tokens=3" %%B in ('ping -n 1 -l 1 %%A ^|findstr Reply') do (
set IPadd=%%B
echo %%A,!IPadd:~0, -1!>>Results.csv
))
pause
You could use errorlevel set by findstr to substitute return string(s) if 'Reply' is not found:
('ping -n 1 -l 1 %%A ^|findstr Reply ^|^| echo Not found Failed:')
where || (escaped here because of for context with ^) means execute only if previous command failed.
As a side note, you should be aware that ping messages are system language dependent (they are translated to language of OS) so 'Reply' as success indicator works only for English versions.
This may not be directly what you are looking for, but I had a similar task: run ping and report success or failure. I'll leave extracting the IP address to you - seeing as you have already done it.
The problem with ping is that it returns success upon name resolution, whether packets get lost or host is unreachable (will report 0% Loss) is irrelevant.
FOR %%a IN (
google.com
a.b.c.d
) DO #FOR /F "delims=" %%p IN (
'PING -w 100 -n 1 %%a ^| findstr ^"Reply Request fail name^"'
) DO #(
ECHO "%%p" | FINDSTR TTL >2 && echo %%a, success, %%p || echo %%a, failed, %%p
) >> Results.csv
Logic: Ping once, filter only lines with the one of the words listed. If TTL exists in resulting line (output to STDERR or NUL to avoid output pollution) echo success, else echo failed.
I'm on English Windows, words will have to be adjusted for other languages.
EDIT:
FOR %%a IN (
google.com
a.b.c.d
) DO #FOR /F "delims=" %%p IN ('PING -n 1 %%a ^| findstr TTL ^|^| echo Failed') DO #(
ECHO "%%p" | FINDSTR TTL >2 && (for /f "tokens=3" %%b IN ("%%p") do #echo %%a, %%b) || echo %%a, failed, %%p
)
Less dependant on language, works only for IPv4, added IP extraction.
Filter ping output for TTL, set output to "Failed" if TTL not found.
If output string contains TTL, extract IP and echo host and IP, else echo host name and output string.

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