How to extract string in batch file? - batch-file

I am trying to extract IP of source of Remote Desktop Connection using,
FOR /F "tokens=3 USEBACKQ" %%F IN (`netstat -n ^| find "3389" ^| find "ESTABLISHED" /c`) DO SET /A IP=%%F
ECHO %IP%
But this way the IP variable contains IP along with the port 192.168.174.129:47523.
How can I extract only the IP part?
I read about the substring functionality in batch but that requires the starting position aling with length but I can't be sure of starting position as last octet of IP might change from 129 to 29 or even 2.

Here's a quick example according to my comment, of using the appropriate delims. It additionally uses findstr.exe instead of find.exe, in order to use a single match string, instead of performing multiple pipes to the same utility.
#Echo Off
SetLocal EnableExtensions
Set "IP="
For /F "Tokens=4 Delims=: " %%G In ('%SystemRoot%\System32\NETSTAT.EXE -n 2^>NUL
^| %SystemRoot%\System32\findstr.exe /R
/C:":3389[ ][ ]*[^ ][^ ]*[ ][ ]*ESTABLISHED"') Do Set "IP=%%G"
If Not Defined IP GoTo :EOF
Echo %IP%
In this case, findstr.exe searches for, and returns, lines output from the NETSTAT.EXE -n command which contain the string :3389 immediately followed by a sequence of one or more space characters, then one or more none space characters, then one or more space characters, then the case sensitive string ESTABLISHED.
Please note however that ESTABLISHED is most likely a language dependent string, so this is unlikely to work universally.

FOR /F "tokens=3 USEBACKQ" %%F IN (`netstat -n ^| findstr "3389" ^| findstr "ESTABLISHED"`) DO (
for /f "delims=:" %%a in ("%%F") do set IP=%%a
)
echo %IP%
I replace find to findstr because find not search text in my machine. The second FOR with delims=: split 192.168.174.129:47523 in two parts. First part is IP address.

Related

How to use a ending number as a variable

I'm trying to figure out how to echo %findstr% to only display the number after this word
filename.txt
"ncui": 8888,
I would like to echo only 8888 so I can use it as a set number=%findstr% to another script
I found this so far
#echo off
findstr /c /i "\<ncui\>" "filename.txt"
I tested this several ways and doesn't work, I only get this "ncui": 8888,
I found serval scripts here but none worked since all where designed to find words without " and :
Any Help would be great
Here are the two possibilities, from my comment, each now split to shorter lines, ready just be pasted into your own batch file.
The first works only if the target string contains just number characters, whereas the second is for more general target strings.
For /F "Tokens=2 Delims=:" %%G In ('%SystemRoot%\System32\findstr.exe
/RIC:"\"ncui\": " "filename.txt" 2^>NUL') Do Set /A number=%%G 2>NUL
For /F "Tokens=2 Delims=:, " %%G In ('%SystemRoot%\System32\findstr.exe
/RIC:"\"ncui\": " "filename.txt" 2^>NUL') Do Set "number=%%G"

Only run code when connected to wifi Batch

I need to run a batch file only if it's connected to Wifi and specifically not Bluetooth LAN
I have this code but it returns this and still runs the code while an internet connection isn't present
Node - DEVICENAME
ERROR:
Description = Invalid query
Code:
#echo off
For /f "usebackq" %%A in (
`wmic path WIN32_NetworkAdapter where 'NetConnectionID="Wi-Fi"' get NetConnectionStatus`
) do if %%A equ 7 (goto end)
<code to run>
:end
You don't need a for loop:
wmic path WIN32_NetworkAdapter where 'NetConnectionID="Wi-Fi"' get NetConnectionStatus |find "7" >nul && goto :eof
echo code to run
If you want to make it more secure, instead of find "7" use findstr /rc:"^7 *$"
(your original approach fails because the = has to be escaped: ... where 'NetConnectionID^="Wi-Fi"' get ... and due to the unusual wmic output, there are CR in your %%A, which messes up the if syntax; You can see both issues with echo on (at least you can see that strange things happen))
The output of WMIC is also the reason for that strange findstr pattern, I used. (there are trailing spaces after the 7).
If you don't already know the name of the wireless interface connection, (which is a configurable property), then you could probably use something more like this:
#For /F Tokens^=6^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe NIC
Where "Not NetConnectionID Is Null And NetConnectionStatus='2'" Get
NetConnectionID /Format:MOF 2^>NUL') Do #%SystemRoot%\System32\netsh.exe WLAN^
Show Interfaces 2>NUL | %SystemRoot%\System32\findstr.exe /E /L ": %%G" 1>NUL^
&& <code to run>
If your target systems are still using Windows 7, (which has a known issue locating some of the XSL files used in the /Format option), then the following alternative may work for you:
#For /F "Skip=1 Delims=" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe NIC Where
"Not NetConnectionID Is Null And NetConnectionStatus='2'" Get NetConnectionID
2^>NUL') Do #For /F "Tokens=*" %%H In ("%%G") Do #%SystemRoot%\System32\netsh.exe^
WLAN Show Interfaces 2>NUL | %SystemRoot%\System32\findstr.exe /E /L ": %%H" 1>NUL^
&& <code to run>
You would obviously change your provided, and replicated above, <code to run>, to one or more actual valid commands

Find multiple strings in multiple lines

I am making a script that can find multiple strings in an command output. For example, here is my output after running the command:
Mount Dir : D:\mount
Image File : F:\sources\boot.wim
Image Index : 1
Mounted Read/Write : No
Status : Needs Remount
I want the batch file to find the strings "D:\mount" and "Needs remount" in the output and they have to both match to give an output, but the problem is it keeps showing the wrong string:
Dir
Press any key to continue...
Needs
Press any key to continue...
I know the problems are in the delimiters, but even if I change it, the results are still the same. Here is the code that I used:
#echo off
for /f "tokens=2 delims=: " %%a in ('dism /get-mountedimageinfo ^| findstr /i /c:"Dir" /c:"status"') do (
#echo %%a
pause
)
Please help me out. Thanks in advance
Your issue is this:
for /f "tokens=2 delims=: " %%a in (...
"delims=: " doesn't mean "delimit by colon plus space", but "delimit by colon and space" (delimters are one-char only; a string is translated into several one-char delimiters).
So tokens=2 is not what you need. You need the string after the (first) colon:
for /f "tokens=1,* delims=:" %%a in (...
where %%a is the part before the first colon and %%b is the part after the first colon (* means "do not tokenize the rest, but take it as one token"). Sadly the space after the colon is part of %%b then, but you can delete it (when needed) with substring substitution:
set "line=%%b"
set "line=!line:~1!"
(of course, you need delayed expansion for that.
Or more elegant with another for:
for /f "tokens=1,* delims=:" %%a in ('dism /get-mountedimageinfo ^| findstr /ibc:"Mount Dir" /ibc:"Status"') do (
for /f "tokens=*" %%c in ("%%b") do (
echo "%%c"
)
)
Edit
According to your comment, you want to know if both the literal path D:\mount and the string Needs Remount occur in the output? Then the following approach is more straigthforward:
for /f %%a in ('dism /get-mountedimageinfo ^| findstr /ixc:"Mount Dir : D:\mount" /ixc:"Status : Needs Remount"^|find /c ":"') do set count=%%a
if %count%==2 echo both strings found
(search for both strings and count the number of lines; compare with expected "2"; No need to actually extract the strings)

How to auto detect interface that connected to the internet

So i have remote machine with simple .bat file:
C:\Program Files\Wireshark\tshark.exe -i 1 -w c:\file.pcap
This command start Tshark process and start sniffing
Now my problem is that i start this .bat file in several machines and in each machine the correct interface is different so with the commend Tshaek -D i can get all the interfaces with the index numbers but from here i need to know which interface is the one the connected to the internet.
And of course i need to do that inside my.bat file and this need to be my interface number (in my example the interface number is hard code and equal to 1)
Any suggestions ?
This is very hacky, but should do.
#echo off
for /f "tokens=2 delims=:" %%i in ('ipconfig ^|findstr "IPv4"') do (
ping -n 1 -S%%i google.com |findstr /i reply
if not errorlevel 1 for /f %%a in ('ipconfig ^| findstr /I /N "%%i"') do set cnt=%%a
)
set /a cnt-=5
for /f "tokens=1* delims=:" %%i in ('ipconfig ^|more +%cnt%') do set adap=%%i & goto runts
:runts
set adap=%adap:*adapter =%
for /f "usebackq delims=." %%i in (`""C:\Program Files\Wireshark\tshark.exe" -D | findstr /I "%adap%""`) do (
"C:\Program Files\Wireshark\tshark.exe" -i %%i -w c:\file.pcap
)
What we do is, run ipconfig and get all IPv4 addresses and use each as source to ping google.com. Using findstr we then match reply and then errorlevel 0 will determine whether the adapter was the active one.
Now we simply go up 5 lines to get the description of the adapter, then we findstr that adapter using tshark -D and simply run the full tshark command.
Note, this will be completely different if you use IPv6.

Reading out put of previous command in bat command file

I am very new to batch programming, I am trying to write a batch file that is a fake virus. I need to obtain the IP address from the previous command IPCONFIG into the variable VarIP. Can you help me?
My code:
echo off
echo Trying to hack your computer
ipconfig
echo Now hacking your IP
ping -t VarIP
echo on
pause
It's pretty simple to extract part of the output from any console command by using find to eliminate the lines in the output that you do not want, then using the for command to extract a portion of the line found by find:
#echo off
setlocal ENABLEDELAYEDEXPANSION
for /f "tokens=2 delims=:" %%i in ('ipconfig ^| find /i "IPv4 Address"') do (set VarIP=%%i&set VarIP=!VarIP: =!)
ping -t !VarIP!
endlocal
Hopefully you are just creating a practical joke on a friend and aren't up to anything more nefarious.
Another Version without "Tokens" for NT :
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('ipconfig ^| find /i "IPv4 Address"') do (set VarIP=!%%a%!)
ping -t %VarIP%
This is a useful method to get IP info:
#echo off
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get IPAddress /value | find "I" "') do echo IPv4 %%~a IPV6 %%~b
pause

Resources