Echo IP Location from txt - batch-file

I am currently trying to ping a list of hostnames, preferably one at a time, and then use nslookup on that hostname. If the hostname in nslookup matches up with the hostname first used, then I would like to use the IP to check against another file (called home.txt) that would contain the location.
What I have so far:
#Echo Off
If '%1'=='' GOTO Syntax
Echo Running Script and Saving Results to Results.CSV
Echo Script Run %date% %time% >> Results.csv
For /F %%i in (%1) do Call :StartPing %%i
Goto :eof
:StartPing
PING %1 -n 1 | FIND /i "TTL" > nul && goto Success
PING %1 -n 1 | FIND /i "timed" > nul && goto Timedout
PING %1 -n 1 -w 400 | FIND /i "TTL" > nul || goto ErrorMsg
:Success
for /F "tokens=3" %%a in ('ping %1 ^| find /i "TTL"') do set Address=%%a
for /F "tokens=2" %%a in ('ping -a %Address::=% ^| find /i "pinging"') do set HostName=%%a
set IPAddress=%Address::=%
echo %1, %IPAddress%,%Hostname%
echo %1, %IPAddress%,%Hostname% >> Results.csv
NSLOOKUP %IPAddress% | FIND /i "Name" = "%Hostname%" goto home
:home
echo %IPAddress% home.txt
Goto :EOF
:Timedout
Echo %1, Request timed out.
Echo %1, Request timed out. >> Results.csv
:ErrorMsg
Echo %1, Ping request could not find host.
Echo %1, Ping request could not find host. >> Results.csv
goto :eof
:Syntax
echo . . .
goto :eof
An example of what home.txt might contain:
10.102.6.43 = 2J
IE, just a bunch of IP ranges mapped to office locations.
Ideally, the script should then make a popup box showing the location of the IP address, or just echo it on-screen.
Any ideas?
Made some changes and tested a few things, here is what i have so far.
#echo Off
#cls
if '%1'=='' GOTO Syntax
echo Running Script and Saving Results to Results.CSV
echo Script Run %date% %time% >> Results.csv
for /F %%i in (%1) do Call :StartPing %%i
goto :EOF
:StartPing
PING %1 -n 1| FIND /i "TTL" > nul && goto Success
PING %1 -n 1| FIND /i "timed" > nul && goto Timedout
PING %1 -n 1 -w 400 | FIND /i "TTL" > nul || goto ErrorMsg
:Success
for /F "tokens=3" %%a in ('ping %1 ^| find /i "TTL"') do set Address=%%a
for /F "tokens=2" %%a in ('ping -a %Address::=% ^| find /i "pinging"') do set HostName=%%a
set IPAddress=%Address::=%
for /f "tokens=2" %%b in ('nslookup %IPAddress%^|find /i "Name"') do set fqdn=%%b
echo %1, %IPAddress%,%Hostname%
echo %1, %IPAddress%,%Hostname% >> Results.csv
goto :EOF
:Timedout
Echo %1, Request timed out.
Echo %1, Request timed out. >> Results.csv
:ErrorMsg
Echo %1, Ping request could not find host.
Echo %1, Ping request could not find host. >> Results.csv
goto :EOF
:Syntax
echo . . .
goto :EOF
:EOF
echo this is the END OF FILE
pause
Every time I run hh.bat host.txt, everything runs fine until it hits the nslookup part, then it creates between 1500 and 3000 processes in windows task manager. without the NSLOOKUP part hh.bat works fine.
I had the nslookup part in a separate script called nslookup.bat which worked fine for a little while, and now it does not want to work. create that amount of processes everytime...
testing in a Hyper-V environment with 3 windows 7 pcs and a DC.

Related

Need Batch command getting mac address and compare on a txt file?

How to get pc mac address and restart PC if mac is not on the list.txt?, i only have this getting mac command,
for /f "tokens=3 delims=," %%a in ('"getmac /v /fo csv | findstr Ethernet"') do set MAC=%%a
echo MAC address of this computer is %MAC%
You use getmac and pipe the result through findstr to filter on the required network adaptor.
You store the result into a variable ThisPCMAC
You use the type command to get the content of the list.txt file piped through findstr to filter on ThisPCMAC.
You store the result into a variable FoundMAC.
If FoundMAC is defined you goto :norestart
If FoundMAC is not defined you goto :restart
In :restart, you call shutdown /r with the required additional params
If mistaken, you can call shutdown /a in the allotted time (10 minutes here, see /t 600).
For further help, see shutdown /?
The 2 files should be in the same directory.
Example content of list.txt:
FF-AA-BB-CC-DD-FA
FF-AA-BB-CC-DD-FB
FF-AA-BB-CC-DD-FC
Content of RestartIfThisPCMACnotInList.bat:
#echo off
set ScriptPath=%~dp0
set ThisPCMAC=
set FoundMAC=
echo.
echo ScriptPath = %ScriptPath%
for /f "tokens=3 delims=," %%a in ('"getmac /v /fo csv | findstr Ethernet"') do set ThisPCMAC=%%a
echo.
echo MAC address of this computer is %ThisPCMAC%
for /F "usebackq delims==" %%b in (`"type %ScriptPath%list.txt | findstr %ThisPCMAC%"`) do set FoundMAC=%%b
if DEFINED FoundMAC (
goto :norestart
) else (
goto :restart
)
:norestart
echo.
echo Found %FoundMAC% in %ScriptPath%list.txt: Nothing to do.
goto :end
:restart
echo.
echo %ThisPCMAC% not found in %ScriptPath%list.txt: Restarting...
echo.
echo shutdown /r /f /t 600 /d p:00:00
shutdown /r /f /t 600 /d p:00:00
echo.
echo Cancel restart with the following command:
echo shutdown /a
goto :end
:end
echo.
echo %~fp0 ended.
pause
Example output for :norestart:
C:\test\>RestartIfThisPCMACnotInList.bat
ScriptPath = C:\test\
MAC address of this computer is "FF-AA-BB-CC-DD-FA"
Found FF-AA-BB-CC-DD-FA in C:\test\list.txt: Nothing to do.
C:\test\RestartIfThisPCMACnotInList.bat ended.
Press any key to continue . . .
Example output for :restart:
C:\test\>RestartIfThisPCMACnotInList.bat
ScriptPath = C:\test\
MAC address of this computer is "FF-AA-BB-CC-DD-FD"
"FF-AA-BB-CC-DD-FD" not found in C:\test\list.txt: Restarting...
shutdown /r /f /t 600 /d p:00:00
Cancel restart with the following command:
shutdown /a
C:\test\RestartIfThisPCMACnotInList.bat ended.
Press any key to continue . . .

.bat - ping list of IPs and reply with response time only

I'm stuck on this one, I've managed to create a batch file that imports list of IPs & hostnames but when I test for success or failure, I'd like to output how long it took. I don't know how to capture this and include it in the output. I'm trying to hide the default ping.exe output. Here's my code
#echo off
for /F "tokens=1,2 delims= " %%A in (computers.txt) do (
rem ping -n 1 %%A | findstr /i "TTL=" | find "Reply" > nul
if %errorlevel% == 0 (
echo %%B %%A successful ping in ?? Seconds
echo %%B %%A successful ping [%date%, %time%] >> log.txt
)
)
Pause
I've figured it out:
#echo off
setlocal enableDelayedExpansion
for /F "tokens=1,2 delims= " %%A in (computers.txt) do (
for /f "tokens=7 delims== " %%G in ('ping -n 1 %%A') do (
ping -n 1 %%A >nul
if errorlevel 1 (
echo %%B %%A unsuccessful ping
echo %%B %%A unsuccessful ping [!date!, !time!] >> log.txt
) else if "%%~G" NEQ "of" if "%%~G" NEQ "0" (
set ms=%%~G
set ms=!ms:ms=!
for /f %%Z in ('powershell !ms!/1000') do set second=%%~Z
echo %%B %%A successful ping in !second! seconds
echo %%B %%A successful ping [!date!, !time!] >> log.txt
)
)
)
Pause
Using FOR /F, it is possible to process command output.
As you may see, I have 2 ping -n 1 %%A. It is because FOR /F doesn't capture the ERRORLEVEL generated by the processing command. The first command gets the output, the second gets ERRORLEVEL.
if "%%~G" NEQ "of" if "%%~G" NEQ "0" filters out the unneeded results.
The powershell command converts milliseconds to second(batch file does not support decimal numbers)
I/O example
I don't have any other computers on my network, therefore I tested it with URLs.
Input -> Output
www.google.com A A www.google.com successful ping in 0.002 seconds
www.yahoo.com B B www.yahoo.com successful ping in 0.032 seconds
a.a.a C C a.a.a unsuccessful ping

Run command based on IP address from text file

I've recently changed jobs and I get to get my hands dirty on some scripting which I've always wanted to learn. I was given an existing batch file and wanted to gussy it up. Previously, this batch file would scan an IP addressed that you are prompted to enter. I want to change this to loop the command based on a list of IP addresses from a text file, only I'm having problems doing that.
I figured that I can do this one of two ways:
1) Run a batch file that will get the IP address, then run the 2nd batch based on that IP address.
OR
2) Just use the one existing batch file and change that to loop based on the IP address on each line of the text file.
What would be the better way to go, and how would you accomplish both?
For #1 I tried to do this, but I don't know how to run the command based on what I'm entering. An example of this would be to run batch.bat 192.168.1.1, which in batch.bat it would attempt to ping 192.168.1.1 (Or whatever entered).
Suppose that you have already a text file named : IP_List.txt with this contents :
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
192.168.1.11
192.168.1.12
192.168.1.13
192.168.1.14
192.168.1.15
192.168.1.16
192.168.1.17
192.168.1.18
192.168.1.19
192.168.1.20
www.google.com
www.stackoverflow.com
You can give a try for this batch file : MultiPingTester.bat
#echo off
Title Multi-Ping hosts Tester with colors by Hackoo 2016
call :init
set "MyFile=IP_List.txt"
If Not exist %MyFile% goto error
mode con cols=65 lines=30
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
echo(
call :color 0E " ------- Ping status of targets hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%MyFile%") do (
ping -n 1 %%a | find "TTL=" >nul
if errorlevel 1 (
call :color 0C " Host %%a not reachable KO" 1 & echo Host %%a not reachable KO >>%LogFile%
) else (
call :color 0A " Host %%a reachable OK" 1 & echo Host %%a reachable OK >>%LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
::*************************************************************************************
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
::*************************************************************************************
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
::*************************************************************************************
:error
mode con cols=70 lines=3
color 0C
cls
echo(
echo ATTENTION !!! Check if the file "%MyFile%" exist !
pause>nul & exit
::*************************************************************************************

Pinging Multiple PCs and Adding Text

I'm pretty new to this so please bear with me, and if you require anymore information from me please say. Thanks in advance for your help.
I have this code that pings different PCs then returns back if they are online/offline. I wanted to know if you could add another column once the bat file has ran its ping test so it has the computer name next to it.
#echo off
if exist C:\tools\computers.txt goto Label1
echo.
echo Cannot find C:\tools\computers.txt
echo.
Pause
goto :eof
:Label1
echo PingTest executed on %date% at %time% > C:\tools\z.txt
echo ================================================= >> C:\tools\z.txt
for /f %%i in (C:\tools\computers.txt) do call :Sub %%i notepad C:\tools\z.txt
goto :eof
:Sub
echo Testing %1 set state=alive ping -n 1 %1 | find /i "bytes=" || set state=dead echo %1 is %state% >> C:\tools\z.txt
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
99.1.82.28 is alive
99.1.82.100 is alive
ect.
If possible I would like the bat file to run so it displays this;
The bat file creates a document that shows the following;
PingTest executed on 28/07/2016 at 13:10:28
Computer 1 : 99.1.82.28 is alive
Computer 2 : 99.1.82.100 is alive
ect.
--
Would appreciate any help & guidance on this.
Thanks.
You can try this solution :
#echo off
Title Ping Test
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a : !ip! ALive ok" || set "msg=%%a : !ip! Dead failed to respond"
echo !msg!
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
EDIT : on 29/07/2016 # 12:48
Another version with multi-colors : Special thanks goes to ICARUS for the color function (-_°)
#echo off
Rem Special thanks goes to Iracus for the color function (-_°)
mode con cols=60 lines=20
Title Multi-Ping hosts Tester with Multi-colors by Hackoo
set "URLS=URLS.txt"
set "LogFile=PingResults.txt"
If exist %LogFile% Del %LogFile%
call :init
echo(
call :color 0E "------- Ping Status of Computers hosts -------" 1
echo(
(
echo ******************************************************
echo PingTest executed on %Date% # Time %Time%
echo ******************************************************
echo(
) > %LogFile%
Setlocal EnableDelayedExpansion
for /f "usebackq delims=" %%a in ("%URLS%") do (
for /f "tokens=2 delims=[]" %%b in ('ping -n 1 %%a') do set "ip=%%b"
ping -n 1 %%a>nul && set "msg=%%a - !ip! ALive ok" && Call :Color 0A "!msg!" 1 || set "msg=%%a - !ip! Dead failed to respond" && Call :Color 0C "!msg!" 1
echo !msg! >> %LogFile%
)
)
EndLocal
Start "" %LogFile%
pause>nul & exit
:init
prompt $g
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
exit /b
:color
set nL=%3
if not defined nL echo requires third argument & pause > nul & goto :eof
if %3 == 0 (
<nul set /p ".=%bs%">%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
) else if %3 == 1 (
echo %bs%>%2 & findstr /v /a:%1 /r "^$" %2 nul & del %2 2>&1 & goto :eof
)
exit /b
EDIT : Update On 23/08/2016
http://pastebin.com/zjYwSqUM

How to ping multiple servers and return IP address and Hostnames using batch script?

So I have to use batch only for this. Basically, the server HOSTNAMES are all listed in a txt file. I used the following code to ping all the servers and display their results in a txtfile.
For /f %%i in (testservers.txt) do ping -n 1 %%i >>pingtest.txt
The above pinged all the servers. Now, I want to output the IP addresses and the HOST Names in a separate file. How can I do this?
I know that I can run a for loop searching for words like "TTL" and then look for the 3rd token (for the IP) and words like "PINGING" for the second token(HOSTNAME). But I am having errors and cant display it properly. The reason why I want to output IPs and Hostnames in a different file is to make a list of the DOWN and UP servers.
Help will be appreciated. :)
EDIT: Just so it isn't confusing, wanted to let you guys know there are 3 different files, testservers.txt has the HOSTNAMES in it, pingtest.txt has ping results, and result.txt will have the IPs along with Hostnames with their current status as DOWN or UP.
Well, it's unfortunate that you didn't post your own code too, so that it could be corrected.
Anyway, here's my own solution to this:
#echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=result.txt
>nul copy nul %OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS=ADDRESS N/A
for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS=%%y
if %%x==Reply set SERVER_ADDRESS=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
)
The outer loop iterates through the hosts and the inner loop parses the ping output. The first two if statements handle the two possible cases of IP address resolution:
The host name is the host IP address.
The host IP address can be resolved from its name.
If the host IP address cannot be resolved, the address is set to "ADDRESS N/A".
Hope this helps.
Parsing pingtest.txt for each HOST name and result with batch is difficult because the name and result are on different lines.
It is much easier to test the result (the returned error code) of each PING command directly instead of redirecting to a file. It is also more efficient to enclose the entire construct in parens and redirect the final output just once.
>result.txt (
for /f %%i in (testservers.txt) do ping -n 1 %%i >nul && echo %%i UP||echo %%i DOWN
)
I worked on the code given earlier by Eitan-T and reworked to output to CSV file. Found the results in earlier code weren't always giving correct values as well so i've improved it.
testservers.txt
SOMESERVER
DUDSERVER
results.csv
HOSTNAME LONGNAME IPADDRESS STATE
SOMESERVER SOMESERVER.DOMAIN.SUF 10.1.1.1 UP
DUDSERVER UNRESOLVED UNRESOLVED DOWN
pingtest.bat
#echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.
better do it this way
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)
this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping
overall this looks like this:
#echo off
SetLocal
set log=path/to/logfile.txt
set check=path/to/checkfile.txt
:start
echo. some echo date >>%log%
:check
for /f %%r in (%check%) do (call :ping %%r)
goto :eof
:ping
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)
:error
echo. some errormessage to >>%log%
echo. some blat to mail?
:eof
echo. some good message to >>%log%
Try this
$servers = Get-Content test.txt
$reg=""
foreach ($server in $servers)
{
$reg=$reg+$server+"`t"+([System.Net.Dns]::GetHostAddresses($server) | foreach {echo $_.IPAddressToString})+"`n"
}
$reg >reg.csv
#echo off
set workdir={your working dir. for example - C:\work }
set iplist=%workdir%\IP-list.txt
setlocal enabledelayedexpansion
set OUTPUT_FILE=%workdir%\result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (%iplist%) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
This worked great I just add the -a option to ping to resolve the
hostname. Thanks https://stackoverflow.com/users/4447323/wombat
#echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
This works for spanish operation system.
Script accepts two parameters:
a file with the list of IP or domains
output file
script.bat listofurls.txt output.txt
#echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
set SERVER_ADDRESS=No se pudo resolver el host
for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP')
do (
if %%v==Haciendo set SERVER_ADDRESS=%%z
if %%v==Respuesta set SERVER_ADDRESS=%%x
if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)

Resources