Test if computer is available on network - windows

I work on a company which has many Shop. Each shop has his own IP address :
SHOP 1 = 192.168.1.0/24, SHOP 2 = 192.168.2.0/24, SHOP 3 = 192.168.3.0/24, etc...
I have a number of Windows computers (between 1 and 9) on the same subnet (255.255.255.0) on each shop.
Each computer has a static IP address : 1st = 192.168.1.10, 2nd = 192.168.1.20, 3rd = 192.168.1.30, 4th = 192.168.1.40, etc.
The HQ of my company can deploy softs ONLY on the first computer on each shop (licences issue).
Here, we will try to install Xerox drivers on ALL windows computer on all shop.
I made 3 batch script :
The first, launched as the superadmin of the computer, install a new user with admin rights to install drivers
The second, launched as the new user, install Xerox drivers and set as default the printer.
The third, launched as the superadmin of the computer, try to install Xerox drivers on other computers of the same shop :
Loop over my 9 ip address (for /l %%G in (...) do (...)
For each IP address, test if it ping.
Do a ftp transfer between the computer 1 and the IP address (drivers packages + scripts)
PsExec64.exe to run the first script
PsExec64.exe to run the second script
The first and the second script works perfectly, we'll not speak about them.
Where I need help is on the thrid.
I try 3 scripts :
The first :
set subnet=192.168.1.
for /L %%G in (20, 10, 90) do (
ping -n 1 %subnet%%%G | findstr "TTL="
if %errorlevel%==0 (
echo Ping %subnet%%%G : OK >> log_ping_errorlevel.txt
) else (
echo Ping %subnet%%%G : KO >> log_ping_errorlevel.txt
)
)
Here the log_ping_errorlevel.txt with 2 computers on my subnet :
Ping 192.168.1.20 : OK
Ping 192.168.1.30 : OK
Ping 192.168.1.40 : OK
Ping 192.168.1.50 : OK
Ping 192.168.1.60 : OK
Ping 192.168.1.70 : OK
Ping 192.168.1.80 : OK
Ping 192.168.1.90 : OK`
I tried to surround %errorlevel% and 0 by simple quote but I get the same result.
Here an extract of the output if I run the batch in cmd window :
C:\Temp\Xerox_Install>(
ping -n 1 192.168.1.90 | findstr "TTL="
if '0'=='0' (echo "Ping 192.168.1.90 : OK" 1>>log_ping_errorlevel.txt ) el
se (echo "Ping 192.168.1.90 : KO" 1>>log_ping_errorlevel.txt )
)
It seems that the errorlevel is always = 0 in my script, IDK why.
The second :
set subnet=192.168.1.
for /L %%G in (20, 10, 90) do (
ping -n 1 %subnet%%%G && set pingtest=ok
if '%ping_test%'=='ok' (
echo Ping %subnet%%%G : OK >> log_ping_errorlevel.txt
) else (
echo Ping %subnet%%%G : KO >> log_ping_errorlevel.txt
)
)
Here the log_ping_set.txt with 2 computers on my subnet :
Ping 192.168.1.20 : OK
Ping 192.168.1.30 : OK
Ping 192.168.1.40 : OK
Ping 192.168.1.50 : OK
Ping 192.168.1.60 : OK
Ping 192.168.1.70 : OK
Ping 192.168.1.80 : OK
Ping 192.168.1.90 : OK`
I think the ping command result is always 0 then the setter pingtest can be executed.
The third :
Because I'm stuck with the ping command, I tried the if exist folder on remote computer :
set subnet=192.168.1.
for /L %%G in (20, 10, 90) do (
if exist \\%subnet%%%G\C$\Temp\ (
echo Remote folder reachable >> log_folder_reachable.txt
) else (
echo ERROR 404 - Remote folder not found >> log_folder_reachable.txt
)
)
Here the log_folder_reachable.txt with 2 computers on my subnet :
Remote folder reachable
ERROR 404 - Remote folder not found
ERROR 404 - Remote folder not found
ERROR 404 - Remote folder not found
ERROR 404 - Remote folder not found
ERROR 404 - Remote folder not found
ERROR 404 - Remote folder not found
ERROR 404 - Remote folder not found
It works BUT the if exist timeover is about 160 seconds and I don't want to wait for 160 seconds before going to the next computer...
Can someone help me with any method but not using external tools ?

You should read SO items about delayedexpansion.
if %errorlevel%==0 (
in the first script should be
if not errorlevel 1 (
[obviously, reverse the logical condition and remove the "not"]
if errorlevel 1 means "if errorlevel is 1 or greater than 1" and is interpreted on the run-time value of errorlevel.
Next:
ping -n 1 %subnet%%%G && set pingtest=ok
if '%ping_test%'=='ok' (
should be
set "ping_test="
ping -n 1 %subnet%%%G && set "ping_test=ok"
if defined ping_test (
Notes
you are setting pingtest in your ping command, then you are attempting to test ping_test
Even had the variablename been correct, the purpose for the quotes in an if statement is to combine the contents as a single string. Single-quotes don't cut the mustard, double-quotes are required.
With the code you have, ping_test once set will retain its value for the next loop, you need to clear it before theping.
The replacement code first sets the value of ping_test to nothing. The quotes delimit the variable name and value so that trailing spaces on the line are not included in the value assigned. The ping command then may set the value of ping_test to (ok, but any value other than nothing (ie something) is valid). The if defined command interprets the run-time value of the variable.
The third part - well, getting desperate, but no need to go this far as the changes I've outlined should solve the problem.

In regards to your first set of code where you said you tried to use delayed expansion it should look like this. Tested and works on my network.
#echo off
setlocal enabledelayedexpansion
set subnet=192.168.1.
for /L %%G in (20, 10, 90) do (
ping -n 1 %subnet%%%G | findstr "TTL="
if !errorlevel!==0 (
echo Ping %subnet%%%G : OK >> log_ping_errorlevel.txt
) else (
echo Ping %subnet%%%G : KO >> log_ping_errorlevel.txt
)

Related

Are there certain MAC address vendor codes that don't work on windows or is there something else wrong with my code?

Following #Asian's question and my recent interest in powershell, I tried to replicate the script I provided to answer Asian's question, however I am not having the same success that I did with the batch script. If you do not want to view the previous question, here is my batch-file for changing your MAC Address:
#echo off
dism >nul
if %errorlevel% NEQ 0 goto Elevate
(call )
netsh interface set interface Wi-Fi disable
timeout /t 1 /nobreak >null
netsh interface set interface Wi-Fi enable
choice /c RC /m "Would you like to randomize your MAC adress or customize it?"
if %Errorlevel% EQU 2 goto custom
set loopcount=5
:loop
set /a loopcount=loopcount-1
if %loopcount% LEQ 0 (goto exitloop)
set /a "ascii = %random% * 26 / 32768 + 65"
cmd /c exit /b %ascii%
set "rl1=%rl1%%=ExitCodeAscii%"
goto loop
:exitloop
set MAC="0E%random:~0,2%%rl1:~0,2%%random:~0,2%%rl1:~3,2%%rl1:~-1%%random:~0,1%"
goto after
:custom
echo What would you like to change your MAC address to?
echo Remember to always have the second digit of your MAC address to always be a 2, 6, A, or E
echo Format: AABBCCDDEEFF
echo/
set /p MAC="Input your MAC address here (no spaces or hyphens)> "
:after
reg add "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0011" /v NetworkAddress /d %MAC% /f >null
netsh interface set interface Wi-Fi disable
timeout /t 1 /nobreak >null
netsh interface set interface Wi-Fi enable
echo Operation Successful
echo %mac% is your new MAC address
pause
goto :eof
:Elevate
Echo Error: The requested operation requires elevation
Echo Run file again as admin
Echo Closing file in 10 seconds...
timeout /t 10 /nobreak >nul
goto :eof
I tried to replicate it in powershell, however the script is very volatile on whether it works or not:
[string]$admin = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
if ($admin -eq "False"){
echo "Error: The requested operation requires elevation`nRun file again as administrator"
pause
exit}
rv * -ErrorAction SilentlyContinue
echo "This file will temporarily disable your Wi-Fi adapter"
While (!($C1)){
$choice1 = Read-Host -Prompt "Would you like to proceed? [Y/N]"
switch ($choice1) {
"N" {echo "Ok, press any key to exit this file:"
cmd /c pause > $null; exit}
"Y" {echo "Ok, proceeding with operation"; [int]$C1 = 1; break}
}
if (!($C1)){echo "Invalid input"}
}
rv * -ErrorAction SilentlyContinue
netsh interface set interface Wi-Fi disable;
$getwifi = netsh interface show interface | findstr "Wi-Fi"
if ($getwifi.substring(0,7) -ne "disable"){echo "Unexpected error: Press any key to exit"
cmd /c pause > $null; exit}
echo "Wi-Fi has been succesfully disabled, proceeding with operation"
While (!($C1)){
$choice1 = Read-Host -Prompt "Would you like to randomize your MAC Address or customize it? [R/C]"
switch ($choice1) {
"R" {
$test = #(...) | get-random
<# $test is a random value in a list of 25000+ MAC Address vendor codes provided in
https://gitlab.com/wireshark/wireshark/raw/master/manuf with the colons removed and columns
besides the MAC column removed as well #>
$test2 = [string](get-random -minimum 10 -maximum 99)+(-join ((65..90) | Get-Random -Count 2 | % {[char]$_}));
$test3 = [string](get-random -minimum 1 -maximum 9)+(-join ((65..90) | Get-Random -Count 1 | % {[char]$_}));
$MAC = $test + $test2 + $test3;
$C1 = 1}
"C" {$C1 = 2}
}
if (!($C1)){echo "Invalid input"}
}
if(!($MAC)){
do{
echo "What would you like to change your MAC address to?`nRemember to always have the second digit of your MAC address to always be a number`nFormat: 11BBCCDDEEFF";
$MAC = read-host -prompt "Input your MAC address here [no spaces or hyphens]";
if ($MAC.length -eq 12){$C1 = 1};
if (!($MAC.length -eq 12)){echo "Invalid input: Follow the format"; rv MAC}
} while(!($MAC))
}
reg add "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\0011" /v NetworkAddress /d $MAC /f >$null
netsh interface set interface Wi-Fi enable
echo "Operation Successful"
echo "$MAC is your new MAC address"
pause
Again, $test is a random value in a list of 25000+ MAC Address vendor codes provided in https://gitlab.com/wireshark/wireshark/raw/master/manuf with the colons removed and columns besides the MAC column removed as well. I believe the issue is in the $test variable where the computer will just reject a certain MAC address. If this is not the issue, can someone explain to me what is the issue, and if there are certain codes that will always work in changing the MAC address successfully, please provide me them. Thank you in advance.
Some addresses that work include:
AABBCCDDEEFF
001122334455
00AA11BB22CC
Other variants of 00----------
6E80F12CC8C9
I will write more sample addresses down when I test them.
Try macaddr=$(echo $FQDN|md5sum|sed 's/^\(..\)\(..\)\(..\)\(..\)\(..\).*$/02:\1:\2:\3:\4:\5/') &> /dev/null && echo macaddr. This will generate a random MAC address and echo it to you. This only works in Ubuntu/Bash though.
You can also do (1..12 | %{ '{0:X}' -f (Get-Random -Max 16) }) -join '' in PowerShell.

Save ping results to TXT file

I am trying to build a script that will save some ping result info to a text file. The only info I really need is date, time, ipaddress, % of loss, and average time.
I have been able to make parts of this work.
I can get the time and date to save to the text file but nothing else.
The other problem I'm having is when I do get it to save to a text file it saved 100s of results to the file. I only want it to save the final result. Then when I rerun the file it would add a new entry to the text file.
Here is a sample of what I have been playing with:
#echo on
SET ip=10.22.222.54
#echo. %date% at %time% to %ip%>>PingLogs.txt
ping %ip% -n 1 >>Logs.txt
stop
This is what I expect it to look like when saving to a text file:
06/07/2019 : 21:54 : 10.22.222.54 - 0% - 0ms,
06/07/2019 : 20:18 : 10.22.222.54 - 0% - 0ms,
Use a for /f loop to catch the output of a command. As your command ping output several lines, it needs a lot of analyzing to find out the correct tokens and delimiters to get the desired parts. Then just reassemble them to your needs and put a loop around:
#echo off
set "IP=www.google.de"
:loop
set "loss="
for /f "tokens=1,9 delims=( " %%a in ('ping -n 1 %IP% ^|findstr "%% ms,"') do (
if not defined loss (set "loss=%%a") else (set "average=%%b")
)
echo %date% : %time% : %IP% - %loss% - %average%
goto :loop
(Note: findstr "%% ms," looks for lines that contain a % (has to be escaped with another %) and/or the string ms, - exactly the two lines, we need). You could also use `findstr "loss Average", but then the script would only work on English Windows versions. I like to keep my scripts as language independent as possible.
Output:
07.06.2019 : 19:40:39,37 : www.google.com - 0% - 13ms
07.06.2019 : 19:40:41,25 : www.google.com - 0% - 13ms
07.06.2019 : 19:40:43,24 : www.google.com - 0% - 15ms
07.06.2019 : 19:40:45,25 : www.google.com - 0% - 13ms
07.06.2019 : 19:40:47,24 : www.google.com - 0% - 13ms
Note: date/time format depends on locale settings - yours probably look different.
Note: with ping -n 1 don't expect loss to be anything other than either 0% or 100%
Note: with ping -n 1, Minimum, Maximum and Average all are the same (this script takes Average nevertheless, so if you use something other than /n 1, the output is still what you expect)
If you needed to ensure that the date and time format were always presented in the same way, you could use this .bat file script to call a PowerShell script. Put both of these scripts in the same directory.
=== pip.bat
powershell -NoLogo -NoProfile -File "%~dp0pip.ps1" >pip.txt
=== pip.ps1
$Computers = #('localhost', 'asdfa')
foreach ($Computer in $Computers) {
if ($tc = Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue) {
ForEach-Object {
"{0} : {1} : {2} - {3}% - {4}" -f #(
(Get-Date -f "MM/dd/yyyy")
, (Get-Date -f "HH:mm")
, $tc.Address
, "0"
, $tc.ResponseTime
)
}
} else {
"{0} : {1} : {2} - {3}% - {4}" -f #(
(Get-Date -f "MM/dd/yyyy")
, (Get-Date -f "HH:mm")
, $Computer
, "100"
, 0
)
}
}

Computername variable in cmd

In CMD the following variable will give you the name of the computer: %COMPUTERNAME%
I need a variable that takes a part of the computername.
I need a if statement that checks if the computername contains "KM" at the start and 00 at the end. It should not look at the number between KM and -00
KM100-00
KM200-00
This works here:
echo %computername%| findstr "^KM.*00$" >nul && echo found the right format
You can do this with substring commands, as per the following transcript:
pax> set xyzzy=KM100-00 KM200-00
pax> echo %xyzzy%
KM100-00 KM200-00
pax> echo %xyzzy:~0,2%
KM
pax> echo %xyzzy:~-2,2%
00
pax> if %xyzzy:~0,2%==KM if %xyzzy:~-2,2%==00 echo yes
yes
That final (chained) if statement is the one you're looking for to see if your variable starts with KM and ends with 00.
The expression %X:~Y,Z% will give you the Z characters starting at position Y (zero-based) of the variable X. You can provide a negative value of Y to make it relative to the end of the string.
echo %computername%| findstr /I /b "KM" | findstr /i /e "00" && echo computer name is like KM-XX-00
You can try also with hostname instead of echo %computername%
I recommend you to read this page, which is about substring usage in command prompt.
And why dont you try this;
set str=KM2000-00
echo.%str%
set pre=%str:~0,2%
echo.%pre%
set pst=%str:~-2%
echo.%pst%
IF %pre% == KM( IF %pst% == 00( echo.true ) )
pause

Trouble saving output contents from a batch script

I'm looking to get computers names from my network, so i decided to use this following script :
for /L %%N in (1,1,10) do nslookup 132.147.160.%%N
PAUSE
With this command everything is displaying correctly on the command prompt.
But with this last one not so well :
for /L %%N in (1,1,256) do nslookup 132.147.160.%%N >nslookup.txt
PAUSE
First of all, the command prompt is displaying wrong things (there's a non-desired "1" added and i don't know why):
C:\Users\Toshiba\Desktop>nslookup 132.147.160.1 1>nslookup.txt
C:\Users\Toshiba\Desktop>nslookup 132.147.160.2 1>nslookup.txt
*** serveur1.mycompany.fr ne parvient pas à trouver 132.147.160.2 : Non-exi
stent domain
C:\Users\Toshiba\Desktop>nslookup 132.147.160.3 1>nslookup.txt
*** serveur1.mycompany.fr ne parvient pas à trouver 132.147.160.3 : Non-exi
stent domain
C:\Users\Toshiba\Desktop>nslookup 132.147.160.4 1>nslookup.txt
*** serveur1.mycompany.fr ne parvient pas à trouver 132.147.160.4 : Non-exi
stent domain
[ ... etc]
And also in nslookup.txt
i've got NO MORE THAN this output :
Serveur : serveur1.mycompany.fr
Address: 132.147.160.1
Nom : 132.147.160.256
Address: 60.200.60.100
Please, what am i doing wrong ?
Thank you
try this:
#ECHO OFF &SETLOCAL
for /L %%N in (1,1,10) do nslookup 132.147.160.%%N >>nslookup.txt 2>&1
TYPE nslookup.txt
To remove the error messages from nslookup.txt, simply delete 2>&1.

get the return value of bat file in windows in unix?

i have the following case :-
i write bash file bbb in windows 2003 and but a return value = 3 by exit /b 3 then i execute this bash file from unix by this command :- ssh -l admin host 'cmd /c start c:\bbb' but when i print the return value i get ( 0 ) not ( 3 ) i print this value by `echo $? ' now how i can get a return value "exit code" from windows bash ?
Your return code is being masked by start, you should not be using it in this case.
your $? is the return code of ssh command. I don't have a windows machine to try, you could echo the %errorlevel% after your cmd command

Resources