Variables on telnet - batch-file

I'm pretty new to coding and I needed a little automation batch file.
I usually just open Telnet from CMD and do this:
I type:o 192.168.1.248
And I get connected to the device
I send my string WE1*1RTMP and the device responds with E1*1RTMP
This is correct and everything works.
But I would like to make this an automation without me requiring to type everything, just launch a .bat file.
I was able to do that both with Ncat, creating a bat file that says:
echo WE1*1RTMP | ncat 192.1568.1.248 23and everything works.
I was also able to do it using Plink with a .bat file saying plink.exe -load RECtelnet < *path to a text file containing the WE1*1RTMP command.
Now I need a way to check the response from the device.
When the command is received and executed correctly, the answer I get is E1*1RTMP, but I'd love to have something that check this.
Like if the response I get is the same as this one, everything just disappear after running, but if the response is anything different, like the E10 error I get when I type a command that is not recognized from the device, instead of disappearing the cmd windows just says something like "Hey your command failed" or anything similar.
I could also send this command using SSH, I have another profile with Plink called "REC" that connects me thru SSH, if this is somehow easier to automate compared to telnet.
How can I archive this ?
Thanks to everyone who will try to help.

I Modified the example Script to be much tighter and use yoru command and IP and do telnet instead of SSH etc.
REM Script Name: TelnetToDevice.cmd
#(
SETLOCAL EnableDelayedExpansion
ECHO OFF
REM SETUP Device Connection Details and commands
SET "_PLink.Path=%~dp0plink.exe"
SET "_PLink.Method=-telnet"
REM SET "_PLink.Method=-ssh"
SET "_Device.User=USERNAME"
SET "_Device.PW=PASSWORD"
SET "_Devices.List="192.1568.1.248""
SET "_Devices.Cmd.List="WE1*1RTMP""
SET /A "_Results.Count=0"
)
FOR %%A IN (%_Devices.List%) DO (
FOR %%B IN (%_Devices.Cmd.List%) DO (
FOR /F "Tokens=*" %%C IN ('
ECHO.Y^|%_PLink.Path% %_PLink.Method% %_Device.User%#%%~A -pw %_Device.PW% "%%~B"
') DO (
ECHO.Results is "%%C"
SET /A "_Results.Count+=1"
SET "_Result.!_Results.Count!=%%C"
)
)
)
ECHO.
ECHO.Listing all Variables generated:
ECHO.
SET "_Result."
PAUSE
(
ENDLOCAL
EXIT /B 0
)
Okay if you just need to collect the output from that command, maybe launch another command in response then it's fairly easy to do in CMD using PLINK, and NCAT should work the same.
(I use Plink to connect to our Cisco Devices from CMD to collect Data, and run some simple commands if I get certain responses)
This is done by catching the output from the command by parsing the results in a FOR /F loop.
At the CLI Directly:
NCAT
FOR /F "Tokens=*" %A IN ('
ECHO.WE1*1RTMP^| ncat 192.1568.1.248 23
') DO (
ECHO.%%A
SET "_Result=%%A"
)
PLINK
FOR /F "Tokens=*" %A IN ('
plink.exe -load RECtelnet ^< "C:\path\to\file containing WE1*1RTMP command.txt"
') DO (
ECHO.%%A
SET "_Result=%%A"
)
Note, I assume you know that in the above commands you will need to provide the Username password etc in these cases, as you say these are working commands as stand.
I happen to have a Script that I use to connect to multiple devices and run commands, its over-kill for your needs, and I will write a trimmed down version, but it seemed worthwhile to include it as the example of running in a CMD script:
Here is the shell of the actual CMD Script I use to check and fix our Fibre switches:
#(
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO OFF
REM SETUP Device Connection Details and commands
SET "_PLink.Path=%~dp0plink.exe"
SET "_Device.User=USERNAME"
SET "_Device.PW=PASSWORD"
SET "_Devices.List="IP/Hostname1" "IP/Hostname_2" "IP/Hostname_3" "IP/HostnameN""
SET "_Devices.Cmd.List="show feature ^| inc http" "show system internal flash ^| include Mount" "show system internal flash ^| include tmp" "dir ^| include free" "show system internal dir /var/tmp ^| Inc 'log.+[0-9][0-9][0-9][0-9][0-9][0-9]'" "show environment fan ^| ex ---- ^| ex Filter" "show environment temperature ^| ex ---- ^| ex '('""
REM Setup Log files and Email
CALL :GetDateTime
SET "_Log.Folder=%~dp0Log"
SET "_eMail.Folder=%~d0\Temp"
IF NOT EXIST "!_Log.Folder!" ( MD "!_Log.Folder!" )
IF NOT EXIST "!_eMail.Folder!" ( MD "!_eMail.Folder!" )
SET "_Log.File=!_Log.Folder!\%~n0_Log_!IsoDate!_!IsoTime!.log"
SET "_eMail.File=!_eMail.Folder!\%~n0_eml.tmp"
SET "_eMail.Subject=%~n0 - Log"
ECHO.>"!_eMail.File!"
SET "_SMTPServer=SMTPServerIP"
SET "_RcptTo=Yourname#YourDomain.com"
SETLOCAL DISABLEDELAYEDEXPANSION
)
CALL :Main
(
ENDLOCAL
Exit /b %eLvl%
)
:Main
FOR %%A IN (%_Devices.List%) DO (
CALL :OutEcho
CALL :DateEcho %%~A:
FOR %%B IN (%_Devices.Cmd.List%) DO (
FOR /F "Tokens=*" %%C IN ('
ECHO.Y^|%_PLink.Path% -ssh %_Device.User%#%%~A -pw %_Device.PW% "%%~B"
') DO (
CALL :OutEcho %%~A: %%~C
(
ECHO.%%~C | FIND /I "log" >NUL
) && (
FOR /F "Tokens=1" %%D IN ("%%~C") DO (
CALL :OutEcho %%~A: Deleting: %%~D
FOR %%b IN (
%_Devices.Cmd.DeleteFoundFile%
) DO (
FOR /F "Tokens=*" %%c IN ('
%_PLink.Path% -ssh %_Device.User%#%%~A -pw %_Device.PW% "%%~b%%~D"
') DO (
CALL :OutEcho %%~A: %%~c
)
CALL :OutEcho %%~A: Deleted: %%~D
)
)
)
)
)
)
CALL :SendMail "%_eMail.File%" "%_eMail.Subject%"
GOTO :EOF
:SendMail
ECHO.Sending Email for "%~2"
CALL ECHO CALL "%~dp0mailsend.exe" -domain reval.com -smtp %_SMTPServer% -f %Computername%#reval.com -t %_RcptTo% -sub "%~2" -attach "%~1",text,i
CALL "%~dp0mailsend.exe" -domain reval.com -smtp %_SMTPServer% -f %Computername%#reval.com -t %_RcptTo% -sub "%~2" -attach "%~1",text,i
GOTO :EOF
:DateEcho
(
SETLOCAL
CALL :GetDateTime
)
CALL :OutEcho %TDate% - %*
ENDLOCAL
GOTO :EOF
:OutEcho
ECHO.%*
ECHO.%*>>"%_Log.File%"
ECHO.%*>>"%_eMail.File%"
GOTO :EOF
:GetDateTime
FOR /F "Tokens=1-7 delims=MTWFSmtwfsouehrandit:-\/. " %%A IN ("%DATE% %TIME: =0%") DO (
FOR /F "Tokens=2-4 Skip=1 Delims=(-)" %%a IN ('ECHO.^| DATE') DO (
SET "%%~a=%%~A"
SET "%%~b=%%~B"
SET "%%~c=%%~C"
SET /a "#%%~a=1%%~A - (2%%~A-1%%~A)"
SET /a "#%%~b=1%%~B - (2%%~B-1%%~B)"
SET /a "#%%~c=1%%~C - (2%%~C-1%%~C)"
SET "HH=%%~D"
SET "Mn=%%~E"
SET "SS=%%~F"
SET "Ms=%%~G"
SET /a "#HH=1%%~D - (2%%~D-1%%~D)"
SET /a "#Mn=1%%~E - (2%%~E-1%%~E)"
SET /a "#SS=1%%~F - (2%%~F-1%%~F)"
SET /a "#Ms=1%%~G - (2%%~G-1%%~G)"
SET /a "#TMinutes=((1%%~D - (2%%~D-1%%~D))*60)+(1%%~E - (2%%~E-1%%~E))"
SET /a "#TSeconds=((((1%%~D - (2%%~D-1%%~D))*60)+(1%%~E - (2%%~E-1%%~E)))*60)+(1%%~F - (2%%~F-1%%~F))"
)
)
SET "TTime=%HH%.%Mn%.%SS%"
SET "IsoTime=%HH%.%Mn%.%SS%.%Ms%"
SET "TDate=%yy%-%mm%-%dd%"
SET "IsoDate=%yy%-%mm%-%dd%"
GOTO :EOF
Below is a MUCH tighter script that uses your provided info directly.
REM Script Name: TelnetToDevice.cmd
#(
SETLOCAL EnableDelayedExpansion
ECHO OFF
REM SETUP Device Connection Details and commands
SET "_PLink.Path=%~dp0plink.exe"
SET "_PLink.Method=-telnet"
REM SET "_PLink.Method=-ssh"
SET "_Device.User=USERNAME"
SET "_Device.PW=PASSWORD"
SET "_Devices.List="192.1568.1.248""
SET "_Devices.Cmd.List="WE1*1RTMP""
SET /A "_Results.Count=0"
)
FOR %%A IN (%_Devices.List%) DO (
FOR %%B IN (%_Devices.Cmd.List%) DO (
FOR /F "Tokens=*" %%C IN ('
ECHO.Y^|%_PLink.Path% %_PLink.Method% %_Device.User%#%%~A -pw %_Device.PW% "%%~B"
') DO (
ECHO.Results is "%%C"
SET /A "_Results.Count+=1"
SET "_Result.!_Results.Count!=%%C"
)
)
)
ECHO.
ECHO.Listing all Variables generated:
ECHO.
SET "_Result."
PAUSE
(
ENDLOCAL
EXIT /B 0
)

The simplest way for you to do what you want is likely to:
Install python.
Write this in a text file (e.g. with notepad), and save it as something ending in .py:
import socket
import traceback
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(("192.168.1.248", 23))
mysock.send(b"WE1*1RTMP\n")
read_so_far = b""
while b"E1*1RTMP".startswith(read_so_far):
read_bit = sock.recv(1024)
if read_bit == b"":
print("Didn't get full message; had", repr(read_so_far))
input("Press enter to continue... ")
break
read_so_far += read_bit
if read_so_far.startswith(b"E1*1RTMP"):
print("Got success message")
break
else:
print("Got the wrong message: ", repr(read_so_far))
input("Press enter to continue... ")
except Exception as e:
traceback.print_exc()
input("Press enter to continue... ")
raise
NOTE: The way the lines are indented there is important.
Double-clicking on that file should now do what you want. If something goes wrong, before asking for help here open up a command prompt, cd to the relevant directory and run it at the command line with python myfile.py (or whatever you named the file). People here will need that output.
Sometime in the future, pick up a book on python or enroll in a python-focused course on coursera or elsewhere. I've heard good things about "Python for Everybody", but there's loads out there - well over 10% of your local big box book store's computer section these days is books trying to teach you python.

Related

Splitting ip and port in ip:port format using batch

For the program I am currently working on I am taking a value, which is a proxy in ip:port format, I need to be able to split the ip and port to different variables so that a different program that needs ip and port separate will be able to work. The program is basically an automated ip/proxy switcher for minecraft, just for in game reasons, I have all the code working except for the part that actually changed the proxy. I am not getting any error message, only that I don't actually know what code to write. Anyways, here is my code.
#echo off
color b
title minecraft proxy switcher
set nLine=0
echo input full path to text file containing proxies
set /P "filepath=>"
echo end >> %filepath%
:top
cls
set /A nLine=%nLine%+1
echo now at proxy number %nLine%
CALL :ReadNthLine "%filepath%" %nLine%
PAUSE >NUL & goto:top
GOTO :EOF
::***************************************************************************************
:ReadNthLine File nLine
FOR /F %%A IN ('^<"%~1" FIND /C /V ""') DO IF %2 GTR %%A (ECHO Error: No such line %2. 1>&2 & EXIT /b 1)
FOR /F "tokens=1* delims=]" %%A IN ('^<"%~1" FIND /N /V "" ^| FINDSTR /B /C:"[%2]"') DO set http_proxy=%%B
goto finish
::***************************************************************************************
:finish
if %http_proxy%==end (
cls
echo all proxies have been used
echo will return to top of list in 5 seconds
TIMEOUT /T 5 /NOBREAK
set nLine=0
goto top
)
java -DsocksProxyHost=ip -DsocksProxyPort=port -Xmx800m -jar MinecraftLauncher.exe
echo New ip is %http_proxy%
echo waiting for user input
echo press any key for a new ip
pause
goto top
Any help is greatly appreciated, also if you notice something else that's badly written or incorrect in my code please tell me.
split the string with a for, using proper tokens and delimiters:
set "line=192.168.1.1:8080"
for /f "tokens=1,2 delims=:" %%a in ("%line%") do (
set server=%%a
set port=%%b
)
echo Server %server% Port %port%
here is a basic code skeleton which processes the file line after line (your way works, but this is way easier):
#echo off
set /p "filepath=File: "
:top
set n=0
for /f "tokens=1,2 delims=:" %%a in (%filepath%) do call :process %%a %%b
timeout 5
goto :top
:process
echo trying %n%
set /a n+=1
echo host: %1
echo port: %2
pause
goto :eof

Redirecting default printer (which is unknown) to LPT3

I'm trying to use the same script "prnmngr.vbs" from Microsoft to redirect the default printer to the LP3 port. I guess this is the most effective and standard way to detect default printers that I found so far but no success so far. I would like to keep it really simple using a .cmd file.
The code below will map the default printer using "WMIC" but it will not redirect to any LPT:
#echo off
FOR /F "tokens=2* delims==" %%A in (
'wmic printer where "default=True" get name /value'
) do SET DefaultPrinter=%%A
exit
My goal as I said is to Redirect the unknown default printer to the LP3 on the unknown computer and it will be great if the result from prnmngr.vbs can be parsed somehow in order to map the Default Printer to the LP3 port. Or to modify the prnmngr.vbs to do the usual command :
net use lpt3 \\computername\sharedprinter
So far I just can't handle the whole VBS coding to do what I need. I got confused with all the functions inside.
The command below will map the printer without any problems only if you have both \Servername and \Sharedprinter but on my case they will be unknown.
Cscript C:\Windows\System32\Printing_Admin_Scripts\en-US\prnmngr.vbs -ac -p "\\servername\sharedprinter"
The Default printer could be a shared network printer or a USB/WiFi and obviously the computer name will also be unknown. I can't check one by one between 5000 machines or users to search and get their devices to give them a command to map their printers on their own every time they execute their application!
I just been told that the name "Imprimant" is the name all the Local Printers shared name will be used so as long as this name doesn't change at all it should be fine.
But at the moment this script is working only for the 1st case (:Shared) and the Local case is not working at all. If I invert the ERRORLEVEL it will work the (:Local) and Not the (:Shared).
But so far I got a new scrip and it goes like this:
#echo off
FOR /F "tokens=2* delims==" %%A in ('wmic printer where "default=True" get name /value ' ) do (
setlocal EnableDelayedExpansion
set DefaultPrinter=%%A
echo %DefaultPrinter% |find "\\"
if ERRORLEVEL EQU 1 (goto Local
else (
if ERRORLEVEL EQU 0 goto Shared
)
:Shared
net use lpt3 "%DefaultPrinter%"
goto end
:Local
net use lpt3 "\\%computername%\Imprimant"
goto end
)
:end
exit /B
Is there something missing?
Voila, here you go !! The final script works fine.
#echo off
if not "%minimized%"=="" goto :minimized
set minimized=true
start /min cmd /C "%~dpnx0"
set minimized=
goto :EOF
:minimized
echo Erasing previous mappings from LTP3...
net use lpt3 /d >nul
echo Detecting Default Printer ...
FOR /F "tokens=1-3* skip=2 delims==" %%A in ('wmic printer where "default=True" get name^,servername^,sharename /value ' ) do (
setlocal EnableDelayedExpansion
set DefaultPrinter%%A=%%B
)
echo Default Printer: %DefaultPrinterName%
REM Is this a Local or Network queue?
echo %DefaultPrinterName% |find "\\" >nul
if %errorlevel%==0 ( goto Shared ) else ( goto Local )
:Shared
echo Mapping to LPT3 over %DefaultPrinterServerName%\%DefaultPrinterShareName%
net use lpt3 "%DefaultPrinterServerName%\%DefaultPrinterShareName%"
goto End
:Local
echo Using a Local Printer
IF NOT "%DefaultPrinterShareName%"=="" (
echo Mapping to LPT3 over \\localhost\%DefaultPrinterShareName%
net use lpt3 "\\localhost\%DefaultPrinterShareName%"
) ELSE (
echo Mapping to LPT3 over \\localhost\Impriman
net use lpt3 \\localhost\Impriman
)
:End
exit >> our you can attach other instructions to continue doing some tasks.
So this script will do what I meant to do.

Determining OS version via Scripting

I found this script on another site but I can not get it to work and I don't know batch scripting that well
Set objWshShell = WScript.CreateObject("WScript.Shell")
strOSVersion = objWshShell.RegRead("HKLM\Software\Microsoft\Windows NT\CurrentVersion\CurrentVersion")
If strOSVersion = "5.1" Then
Debug.WriteLine("Windows XP")
Rem Insert Windows XP Statements
ElseIf strOSVersion = "6.0" Then
Debug.WriteLine("Windows Vista")
Rem Insert Windows Vista Statements
ElseIf strOSVersion = "6.1" Then
Debug.WriteLine("Windows 7")
Rem Insert Windows 7 Statements
End If
now if I run this I get the error on the second line
'strOSVersion' is not recognized as an internal or external command
operable program or batch file.
= was unexpected at this time.
I do not know why
It's a VB script. You can save in a file named like test.vbs
Then open a command prompt, change directory to where you saved the file. At the prompt type cscript test.vbs.
Before that, I changed the Debug.WriteLine calls to WScript.Echo instead.
This is a Batch Script (.bat) that I've put together and use often for determining OS.
#ECHO OFF
SetLocal
REM --------> EDIT BELOW <--------
REM Edit below if you would like to audit the pc's you run this on and store the information in a file, either T or F (for True or False)
set storeValue=T
REM Edit below the location on a network drive that you can write to
set sharePath=\\servername\sharepath
REM -----> DO NOT EDIT BELOW <-----
IF NOT EXIST C:\Temp MD C:\Temp
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" | findstr ProductName>C:\temp\osver.txt
set osver=
set tempLoc=C:\Temp
FOR /F "tokens=3* delims= " %%I IN (%tempLoc%\OSver.txt) DO SET osVer=%%I %%J
echo.-----------------------------------------
echo. You are running: %osVer%
echo.-----------------------------------------
IF '%storeValue%'=='F' goto end
IF '%storeValue%'=='T' goto storeValue
:storeValue
ipconfig |findstr IPv4>c:\temp\ipadd.txt
REM FOR /F "tokens=12* delims=." %%A IN (%tempLoc%\IPAdd.txt) DO SET IPAdd=%%A.%%B
FOR /F "tokens=2* delims=:" %%A IN (%tempLoc%\IPAdd.txt) DO SET IPAdd=%%A
IF EXIST %sharePath%\PC_Audit_List.txt goto audit
echo.PC Audit List>%sharePath%\PC_Audit_List.txt
echo.------------------------------------------------------------->>%sharePath%\PC_Audit_List.txt
goto audit
:audit
echo.%computername% - %IPAdd% - %osVer%>>%sharePath%\PC_Audit_List.txt
goto end
:end
IF EXIST %tempLoc%\OSver.txt del %tempLoc%\OSver.txt /f /q
IF EXIST %tempLoc%\IPAdd.txt del %tempLoc%\IPAdd.txt /f /q
EndLocal
pause
exit
I'm sure this will suit your needs, I've included an option for you to write the IP, Name and then the Version into a file.
#echo off
setlocal EnableDelayedExpansion
::Identify OS
for /F "delims=" %%a in ('ver') do set ver=%%a
set Version=
for %%a in (95=95 98=98 ME=ME NT=NT 2000=2000 5.1.=XP 5.2.=2003 6.0.=Vista 6.1.=7 6.2.=8 6.3=8.1) do (
if "!Version!" equ "this" (
set Version=Windows %%a
) else if "!ver: %%a=!" neq "%ver%" (
set Version=this
)
)
::Identify bit
if exist "%SYSTEMDRIVE%\Program Files (x86)" (
set Type=64 bit
) else (
set Type=32 bit
)
::Display result
echo %Version% %Type%
echo/
pause
Copied from: http://www.dostips.com/forum/viewtopic.php?f=3&t=4387

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!
)

Remotely check file size and get report

This script tries to:
get an input from a txt file, which is a list of computer names,
check if a log file on a computer from the list is bigger than 1000 bytes,
create a txt report with the names of those computers where the log file is more than 1000 bytes,
create another txt report with the names of the computers where the file is less than 1000 bytes.
However, something goes wrong. Any help could be nice.
#echo off
for /f "tokens=*" %%I in (computernames.txt)do call :checksz %%I
goto :eof
:checksz
setlocal
set file="\\%1\c$\data\info.log"
set min=1000
FOR /F "usebackq" %%A IN ('%file%') DO set size=%%~zA
if %size% GTQ %min% (
echo. %1 >>logsizemin.txt
) ELSE (
echo. %1>>logsizemax.txt
)
Hello everyone,
thanks for your valuable support. I congratulate whith those who conceived and built this site is really well done and useful.
I made some modifications to the script that you have kindly suggested to incorporate other features, but something is not working as I would like .. as you can view I use editv32 in order to hide password in my batch, the principle is the same but as you can see after checking the size of the log, "maxlongsize.txt" is used in order to take the names of the PCs on which do the next activity. I wish that the activities were performed sequentially on all PCs in the file "logsizemax.txt" with only one authentication at the beginning. I noticed that, for some reason sometimes the file "logsizemin.txt" is not created but i don't understand why. The maximum would be to put in another file such as "computer unreachable" those PCs that are not reached on the network but I have absolutely no idea how implement it. I hope I have sufficiently explained. Sorry for bad English! I think you understand my intention :). Following the batch
#setlocal
#echo off
editv32 -p "Enter username:" USR
editv32 -m -p "Enter password:" PWD
for /f "tokens=1" %%I in (computernames.txt) do call :checksz %%I
endlocal
goto :eof
:checksz
setlocal
set file="\\%1\c$\data\data.log"
set min=1000
type NUL>logsizemax.txt
type NUL>logsizemin.txt
if not exist %file% goto :eof
FOR /F "usebackq delims=" %%A IN ('%file%') DO set size=%%~zA
if %size% GEQ %min% ( echo %1>>logsizemax.txt ) ELSE ( echo %1>>logsizemin.txt )
endlocal
#setlocal
for /f "tokens=1" %%I in (logsizemax.txt) do call :sw %%I
endlocal
goto :eof
:sw
echo.
echo *****************************************
echo * VBS & Deploy script *
echo *****************************************
echo.
echo Run VBS and deploy script .....
psexec \\%1 -u %USR% -p %PWD% cscript "\\rep\Reg.vbs"
psexec \\%1 -u %USR% -p %PWD% cmd /c "\\rep\deploy.cmd"
echo.
echo **************************
echo * EXE Run *
echo **************************
echo.
echo Running exe .....
psexec -u %USR% -p %PWD% \\%1 "c:\Program Files\test.exe"
echo.
echo ***********************************
echo * Exe application launched *
echo ***********************************
echo.
goto END
:END
exit
You can avoid using environment variables and using the second FOR alltogether. Try this simpler version of your bat, with a more generic :checksz routine.
#echo off
for /f "tokens=*" %%a in (computernames.txt) do (
call :checksz "\\%%a\c$\data\info.log" 1000 "%%a"
)
goto :eof
:checksz
if %~z1 GTR %2 (
echo %~3 >> logsizemin.txt
) ELSE (
echo %~3 >> logsizemax.txt
)
goto :eof
see HELP CALL for more information.
Changes: GTG->GEQ, don't surround variable with quotes twice, remove leading space from echo, and a little clean up.
#setlocal
#echo off
for /f "tokens=1" %%I in (computernames.txt) do call :checksz %%I
endlocal
goto :eof
:checksz
setlocal
set file=\\%1\c$\data\info.log
set min=1000
if not exist %file% endlocal && goto :eof
FOR /F "usebackq delims=" %%A IN ('%file%') DO set size=%%~zA
if %size% GEQ %min% ( echo %1>>logsizemin.txt ) ELSE ( echo %1>>logsizemax.txt )
endlocal
goto :eof
edit: updated per comments from PA and Andriy M - endlocal if the file doesn't exist, and remove \ update note.

Resources