Automate telnet port testing on Windows 7 using batch script - windows

I am using Windows 7 x64. Using a bat script, I need to check whether I am able to connect to some specific ports on a server using telnet. If successfully connected, the server displays a menu, or else a message like this : Connecting To xxxxx...Could not open connection to the host, on port xxxxx: Connect failed.
For my purpose, the server has several ports to be tested and I don't want to complicate things by logging in or navigating menus. I just want a simple output indicating whether the connection was successful or not. Checking for exit status didn't work. I don't want to use Visual Basic. Any idea how check the connection status using a bat script? Currently I check visually and I use the below script to open connections
#ECHO OFF
setlocal EnableDelayedExpansion
echo.
SET /P host_name="Please enter the hostname: "
echo Please enter the port numbers followed by the Enter key:
echo.
set num=0
:Loop
set /a num=num+1
SET /P mwa_port%num%=""
if "!mwa_port%num%!"=="" (goto Start)
goto Loop
:Start
set /a num=num-1
for /L %%i in (1,1,%num%) do (
echo Trying to log into port !mwa_port%%i! of %host_name%
start /min "" "C:\Windows\System32\telnet.exe" %host_name% !mwa_port%%i!
REM echo Exit Code is %errorlevel%
)
:End
endlocal
echo.
SET /P leave="Press any key to exit.."
Here is a sample output of the script :
Please enter the hostname : abcdefg.hijkl.mnop
Please enter the port numbers followed by the Enter key:
10001
10002
10003
10004
10005
Trying to log into port 10001 of abcdefg.hijkl.mnop
Trying to log into port 10002 of abcdefg.hijkl.mnop
Trying to log into port 10003 of abcdefg.hijkl.mnop
Trying to log into port 10004 of abcdefg.hijkl.mnop
Trying to log into port 10005 of abcdefg.hijkl.mnop
Press any key to exit..
It then opens 5 telnet windows in minimized state, each one with a menu on successful login

It's a shame you can't use netcat - are all open source options like it off-limits in your environment?
Even without open source tools, you can still accomplish this task with PowerShell.
Here's a sample PS script that will try to connect to port 23 on $remoteHost and exit 0 on success, and 1 on failure. (If you need to do more work once connected, a few examples of more complex PowerShell telnet clients are available on the web, such as this one.)
Place the code in the file "foo.ps1", then run in cmd.exe (or from a .bat file) with "powershell -File foo.ps1". When it exits, the exit code will be stored in %errorlevel%.
Note you may need to modify your PowerShell script execution policy (or use the "-ExecutionPolicy Bypass" cmdline option) to allow execution of the script - for more info see this documentation from MSFT.
param(
[string] $remoteHost = "arbitrary-remote-hostname",
[int] $port = 23
)
# Open the socket, and connect to the computer on the specified port
write-host "Connecting to $remoteHost on port $port"
try {
$socket = new-object System.Net.Sockets.TcpClient($remoteHost, $port)
} catch [Exception] {
write-host $_.Exception.GetType().FullName
write-host $_.Exception.Message
exit 1
}
write-host "Connected.`n"
exit 0

you can use netcat, session log:
C:\Users\User>nc -v -t stackoverflow.com 23
stackoverflow.com [198.252.206.16] 23 (telnet): TIMEDOUT
C:\Users\User>echo %errorlevel%
1
C:\Users\User>nc -v -t stackoverflow.com 25
stackoverflow.com [198.252.206.16] 25 (smtp) open
220 SMTP Relay SMTP
421 SMTP Relay SMTP session timeout. Closing connection
C:\Users\User>echo %errorlevel%
0

What do you mean by Checking for exit status didn't work.?
If you un-REM your Exit-code print line, the response will be that ERRORLEVEL will be the value of errorlevel when the FOR loop was parsed - prior to execution.
To display the value as it changes for each invocation of telnet you'd need
...
"C:\Windows\System32\telnet.exe" %host_name% !mwa_port%%i!
echo Exit Code is !errorlevel!
where !errorlevel! is the run-time value of errorlevel.
In all probability, you'd want to suppress the telnet output, so >nul and/or 2>nul may be usefully attached to quieten it down. Possibly youd need to provide telnet with a response - not my area...
Now - if errorlevel doesn't return a usable value, is there any telnet response that can be observed to distinguish between the states in which you are interested?

Related

Windows batch. Put Serial port data in a variable

I have a hardware (battery controller) that send battery voltage over a serial port. It's just 4-digit value+endline ('1232\r\n') every 5 seconds.
I need to read that value and if it's below a treshold shut PC down. It's old WinXP machine where I'm allowed to use CMD only without creating temporary files.
On my home PC I created a test environment with two virtual ports (with com2com utility) and powershell script that emulates hardware:
cls
$port = New-Object System.IO.Ports.SerialPort
$port.PortName = "COM4"
$port.open()
while (1) {
$port.Write("1000"+[char]13+[char]10)
$port.close()
Start-Sleep -Seconds 5
$port.open()
}
Script below has to recieve data and shut down PC if value below treshold. But it doesn't work.
# ECHO OFF
MODE COM5 BAUD=9600 PARITY=n DATA=8 > nul
set tr=1100
FOR /F "usebackq" %%i IN (`TYPE COM5`) DO set x=%%i
IF %x% lss %tr% (ECHO System will shutdown
rem shutdown /s
)
When I run script It's just waits endlessly.
The for /f loop does not output the results of the command line-by-line as received. It waits for the command to complete so, by using type COM5 you will have a running command that does not exit, unless it experiences EOF.
To do this you can redirect its output as input to the for loop
<COM5 (for /L %%i in (0) do set x=%%i)
You have to note though that this will not run as a permanent loop and you'll have to create a permanent loop if you plan on running it continually.

Automating connection to VNC with batch file

I'm trying to create a batch file to automate vnc connections, this is what i came up with:
#echo off
:Begin
set "PASS=123"
set /p IP=Enter IP Address:
echo Connecting...
start /d "C:\Program Files (x86)\UltraVNC\" VNCVIEWER.EXE %IP%
goto Begin
problem is that the program comes up with a second pop up display for the password which is always 123 but i don't know how to make that automatic too, once the process is open how do i make the batch file enter the password as well automatically ?

windows batch file start browser after server restart

I want to create a batch file which will start the tomcat server and after the server is started , I want to open a URL in browser.
In the below solution , the suggestion is to use timeout option .
How to launch application after server startup using batch file?
Is there any other better way to check if tomcat is started and then I can trigger to open the browser.
You can use this:
wmic process list brief | find /i "tomcat"
To see tomcat is running.
You can use powershell too:
test-netconnection -computername <name or ip> -port <port number>
get-process | select-string <process name>
First command will check if the specified port is listening and the second will check if the specified process is running. You can use them in whatever order you see fit and check the output. If the output is not in desired state, you can do sleep and loop again until tomcat is up.
start "" tomcat.exe
:loop
timeout /t 1 >NUL
tasklist /FI "imagename eq tomcat.exe" | findstr /I /C:"tomcat.exe" >NUL
if errorlevel 1 goto loop
chrome.exe http://%url%
tasklist verify, if started program really running. Do not simply trust the program start correctly

Need auto-restart script in batch for minecraft server

I am currently an administrator on a private Minecraft server, though in this case the technical question lies outside the scope of typical minecraft supoort.
I wish to have the batch file that launches the server restart at 12 am and 12 pm, though I have little experience in batch and a cursory google search brings up nothing helpful.
The issue I run into is both that I have no idea if batch CAN execute commands within a java server console, send the commands to save the server and then exit, and restart itself, due to only knowing basic batch functions.
More specifically, I want the batch file itself to run a command in the server window after either 43200 seconds or on each of the 12s, then restart itself. I do not know how to get a batch file to run a command within the server command line, or if it's even possible.
The current batch code is as follows:
#echo off
:Minecraft
echo (%time%) Minecraft started.
java -Xms2048m -Xmx2048m -XX:PermSize=128m -jar FTBServer-1.6.4-965.jar nogui
pause
echo (%time%) WARNING: Minecraft closed or crashed, restarting.
ping 1.1.1.1 -n 1 -w 3000 >nul
goto Minecraft
Any help would be aprreciated. Thanks.
i use this but if you want it to restart it automatically then just delete the :choise part and make a loop from start to restart
#echo off
title minecraft-server-1.8.3
color 0A
prompt [server]:
cls
:start
echo loading server...
java -Xms3G -Xmx3G -jar minecraft_server.1.8.3.jar nogui
cls
:choice
set /P a=do you want to restart[Y/N]?
if /I "%a%" EQU "Y" goto :restart
if /I "%a%" EQU "N" goto :stop
goto :choice
:restart
cls
echo server will restart
TIMEOUT /T 5
cls
goto :start
:stop
cls
echo closing server
TIMEOUT /T 5
exit
ps. replace minecraft_server.1.8.3.jar with the name of your server file
Solution 1:
I would suggest to use the windows task scheduler instead of a batch file. There you can create a task, schedule it to be triggered at 12am/pm and insert any cmd command you want to be executed. However, it's non-trivial to cummunicate with the server console without knowing the specific interface or how to administrate a minecraft server. What you can do is simply kill the server and restart it using the command line.
Solution 2:
If you don't like this solution and don't know how to communicate with the server console you can try this:
Take a look at AutoIt (https://www.autoitscript.com/site/). It's a VERY simple script language which also can simulate click and input from the keyboard. So you can write a script that sets the focus to your server console and types the desired command to restart the server. This AutoIt script can be compiled to an exe file or you can run it as an au3 script.
You should still use the task scheduler to run your exe/script at 12am/pm.
If you need some help writing the AutoIt script I can help you with that.
I wrote a similar program for a friend in AutoIt here is the script i commented the lines you need to config:
HotKeySet("{ESC}", end)
HotKeySet("{F1}", start) ;optional
HotKeySet("{F2}", pause) ;optional
pause() ; starts the pause loop when started
; restarts the server all 12 hours
Func start()
$Path = "PathToYourBatch.bat" ; self explained
While 1
If #HOUR = 00 Or #HOUR = 12 Then ;starts the server at 00 and 12
Run($Path)
EndIf
WEnd
EndFunc
Func pause()
While 1
Sleep(500) ; waits 500 ms to reduce lag
WEnd
EndFunc
Func end()
Exit
EndFunc
You dont need to use the hotkeys but you could easily control the program with them(remote desktop)
You can use a online compiler like (http://www.script-example.com/themen/AutoIT-Online-Compiler.php) or download it from (https://www.autoitscript.com/site/) hope i could help if any further questions with the code ask me.

batch file to detect if wifi adapter is enabled

I tried to complete this commands in cmd but im having trouble fixing it. Can anyone help me?
netsh wlan show networks | FIND "turned off" /I /C
if "dont know what should be here" == 0 (
echo enabled
) else (
echo disabled
)
pause
You're looking for the %errorlevel% variable, which indicates the exit status of the command last executed (in your case find). You have to revert your logic, though, because find returns 0 (i.e. "success") when the adapter is disabled. Also, I'd recommend to do a numeric comparison (equ) instead of a string comparison (==).
if %errorlevel% equ 0 (
echo disabled
) else (
echo enabled
)
All you have to do is attempt to enable it whether or not it's enabled or disabled
netsh interface set interface name="name of adapter" admin=enable || echo already enabled
If the adapter is already enabled then it won't do anything so the double pipes || means if there's an error in the first command it will execute whatever command is after it which is echo "already enabled."
If it says "this network connection does not exist" ignore that, it means the adapter is already enabled.
I put together this code for a batch script. It works like a charm to turn ON/OFF my wireless network connection:
netsh wlan show networks | FIND "Wireless network connection" /I /C
if %errorlevel% equ 1 (wmic path win32_networkadapter where NetConnectionID="Conexión de red inalámbrica" call enable) else (wmic path win32_networkadapter where NetConnectionID="Wireless network connection" call disable)
If you have more than one wireless network connection, change the name for your particular network connection name and that will do.

Resources