How to use netstat -b to find ip from .exe file - cmd

So I was looking for a way that I can use netstat -b and findstr. I tried using it in cmd like this:
netstat -b | findstr "chrome"
But that just gives me output
[chrome.exe]
[chrome.exe]
[chrome.exe]
[chrome.exe]
[chrome.exe]
[chrome.exe]
I want to get ip address as output within the "chrome.exe"

If powershell is an option for you, the command is quite simple:
Get-NetTCPConnection -OwningProcess $(get-process chrome | % { $_.Id }) -ErrorAction SilentlyContinue
With this command you can get all PIDs by process name:
get-process chrome | % { $_.Id }
Then you can filter Get-NetTCPConnection (netstat alternative for powershell) by PIDs with a subshell.
Not all chrome processes have TCP connection established: to have a clean output ErrorAction can be setted to SilentlyContinue

That could be done with a batch file with following code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=chrome.exe"
set "FoundExecutable="
for /F "tokens=1,2 delims=[] " %%G in ('%SystemRoot%\System32\netstat.exe -b 2^>nul') do (
if /I "%%G" == "%FileName%" (
set "FoundExecutable=1"
) else if /I "%%~xG" == ".exe" (
set "FoundExecutable="
) else if defined FoundExecutable if "%%G" == "TCP" (
echo %FileName% %%H
)
)
endlocal
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
if /?
netstat /?
set /?
setlocal /?
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded netstat command line with using a separate command process started in background.

Related

Store a decryption result in a variable and print it command line [duplicate]

I would like to make a bat script that performs an action only if fewer than 2 occurrences of cmd.exe are running. I managed to find a solution that stores the occurrence count in a temporary file, but I find it very inelegant. So my question is how to do the same as below without a temporary file, but rather by storing the occurence count given by #TASKLIST | FIND /I /C "%_process%" in a variable. I saw that there may be a solution with a for loop, but I couldn’t get it to work and anyway I would really prefer a solution based on SET (if this is possible).
#SET _process=cmd.exe
#SET _temp_file=tempfiletodelete.txt
#TASKLIST | FIND /I /C "%_process%" > %_temp_file%
#SET /p _count=<%_temp_file%
#DEL /f %_temp_file%
#IF %_count% LSS 2 (
#ECHO action 1
) ELSE (
#ECHO action 2
)
Edit: This question is similar to Save output from FIND command to variable, but I wasn’t able to apply the solution to my problem and I wanted to know if a solution without a for loop is possible.
The command FOR with option /F and the command or command line specified as set (string inside parentheses) additionally enclosed by ' can be used for processing the output of a command or a command line with multiple commands on one line.
You can use this batch file:
#ECHO OFF
SET "_process=cmd.exe"
FOR /F %%I IN ('%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq %_process%" ^| %SystemRoot%\System32\find.exe /I /C "%_process%"') DO SET "_count=%%I"
IF /I "%_process%" == "cmd.exe" SET /A _count-=1
IF %_count% LSS 2 (
ECHO action 1
) ELSE (
ECHO action 2
)
The command FOR runs in background without a visible console window cmd.exe /C with the command line:
C:\Windows\System32\tasklist.exe /FI "IMAGENAME eq cmd.exe" | C:\Windows\System32\find.exe /I /C "cmd.exe"
TASKLIST option /FI "IMAGENAME eq cmd.exe" filters the output of TASKLIST already to processes with image name (= name of executable) cmd.exe. This makes further processing faster and avoids that a running process with file name totalcmd.exe is counted as cmd.exe as the command line in question does.
The output of TASKLIST written to handle STDOUT is redirected to handle STDIN of command FIND which processes the lines and counts the lines containing cmd.exe anywhere in line. FIND outputs finally the number of lines containing searched string to handle STDOUT of command process running in background.
The redirection operator | must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
FOR with option /F captures everything written to handle STDOUT of executed command process and processes each line. In this case just one line is captured by FOR containing just a number. Therefore no additional options are needed to assign the number assigned to loop variable I by FOR to environment variable _count using command SET.
The goal of this batch file is counting the number of cmd.exe processes already running. As the command line with TASKLIST and FIND is executed by FOR in background with using one more cmd.exe process, it is necessary to subtract the count by one to get the correct result using an arithmetic expression evaluated with SET /A _count-=1. This decrement by one is needed only for counting right the number of cmd.exe processes. It is not necessary for any other process.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
find /?
for /?
if /?
set /?
tasklist /?
You would do it like this, using TaskList in a For loop:
#Set "_process=cmd.exe"
#For /F %%A In ('TaskList^|Find /C /I "%_process%"'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
You can also perform a similar thing using WMIC too:
#Set "_process=cmd.exe"
#For /F %%A In ('WMIC Process Get Name^|Find /C "%_process%"'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
These could be refined further to ensure processes containing the string as opposed to matching it aren't counted:
#Set "_process=cmd.exe"
#For /F %%A In ('TaskList /FI "ImageName Eq "%_Process%""^|Find /C "."'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
 
#Set "_process=cmd.exe"
#For /F %%A In (
'WMIC Process Where "Name='%_process%'" Get Name^|Find /C "."'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
Note:If you're really checking the cmd.exe process, be aware that an the command inside the For loop parentheses is spawned within a new cmd.exe instance, (thereby increasing your count by 1)

BATCH — Store command output to variable

I would like to make a bat script that performs an action only if fewer than 2 occurrences of cmd.exe are running. I managed to find a solution that stores the occurrence count in a temporary file, but I find it very inelegant. So my question is how to do the same as below without a temporary file, but rather by storing the occurence count given by #TASKLIST | FIND /I /C "%_process%" in a variable. I saw that there may be a solution with a for loop, but I couldn’t get it to work and anyway I would really prefer a solution based on SET (if this is possible).
#SET _process=cmd.exe
#SET _temp_file=tempfiletodelete.txt
#TASKLIST | FIND /I /C "%_process%" > %_temp_file%
#SET /p _count=<%_temp_file%
#DEL /f %_temp_file%
#IF %_count% LSS 2 (
#ECHO action 1
) ELSE (
#ECHO action 2
)
Edit: This question is similar to Save output from FIND command to variable, but I wasn’t able to apply the solution to my problem and I wanted to know if a solution without a for loop is possible.
The command FOR with option /F and the command or command line specified as set (string inside parentheses) additionally enclosed by ' can be used for processing the output of a command or a command line with multiple commands on one line.
You can use this batch file:
#ECHO OFF
SET "_process=cmd.exe"
FOR /F %%I IN ('%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq %_process%" ^| %SystemRoot%\System32\find.exe /I /C "%_process%"') DO SET "_count=%%I"
IF /I "%_process%" == "cmd.exe" SET /A _count-=1
IF %_count% LSS 2 (
ECHO action 1
) ELSE (
ECHO action 2
)
The command FOR runs in background without a visible console window cmd.exe /C with the command line:
C:\Windows\System32\tasklist.exe /FI "IMAGENAME eq cmd.exe" | C:\Windows\System32\find.exe /I /C "cmd.exe"
TASKLIST option /FI "IMAGENAME eq cmd.exe" filters the output of TASKLIST already to processes with image name (= name of executable) cmd.exe. This makes further processing faster and avoids that a running process with file name totalcmd.exe is counted as cmd.exe as the command line in question does.
The output of TASKLIST written to handle STDOUT is redirected to handle STDIN of command FIND which processes the lines and counts the lines containing cmd.exe anywhere in line. FIND outputs finally the number of lines containing searched string to handle STDOUT of command process running in background.
The redirection operator | must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
FOR with option /F captures everything written to handle STDOUT of executed command process and processes each line. In this case just one line is captured by FOR containing just a number. Therefore no additional options are needed to assign the number assigned to loop variable I by FOR to environment variable _count using command SET.
The goal of this batch file is counting the number of cmd.exe processes already running. As the command line with TASKLIST and FIND is executed by FOR in background with using one more cmd.exe process, it is necessary to subtract the count by one to get the correct result using an arithmetic expression evaluated with SET /A _count-=1. This decrement by one is needed only for counting right the number of cmd.exe processes. It is not necessary for any other process.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
find /?
for /?
if /?
set /?
tasklist /?
You would do it like this, using TaskList in a For loop:
#Set "_process=cmd.exe"
#For /F %%A In ('TaskList^|Find /C /I "%_process%"'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
You can also perform a similar thing using WMIC too:
#Set "_process=cmd.exe"
#For /F %%A In ('WMIC Process Get Name^|Find /C "%_process%"'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
These could be refined further to ensure processes containing the string as opposed to matching it aren't counted:
#Set "_process=cmd.exe"
#For /F %%A In ('TaskList /FI "ImageName Eq "%_Process%""^|Find /C "."'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
 
#Set "_process=cmd.exe"
#For /F %%A In (
'WMIC Process Where "Name='%_process%'" Get Name^|Find /C "."'
) Do #If %%A Lss 2 (Echo Action 1) Else Echo Action 2
#Pause
Note:If you're really checking the cmd.exe process, be aware that an the command inside the For loop parentheses is spawned within a new cmd.exe instance, (thereby increasing your count by 1)

Looking for command to get only "Root Path"

When I am executing command logman FabricTraces in a command prompt window, I get output many attributes and their values as shown below:
Name: FabricTraces
Status: Running
Root Path: C:\ProgramData\Windows Fabric\Fabric\log\Traces\
Segment: On
Schedules: On
Segment Max Size: 128 MB
Run as: SYSTEM
Is there any command to get only Root Path value?
You can get a similar effect of the grep utility in windows by using findstr:
logman FabricTraces | findstr "Root Path:"
-
Source: https://www.mkyong.com/linux/grep-for-windows-findstr-example/
for /f "tokens=1* delims=:" %%a in ('logman FabricTraces^|find "Root Path"') do for /f "tokens=*" %%r in ("%%b") do set rootpath=%%r
echo %rootpath%
first for is to get the desired string, second for is to remove leading spaces.
According to your comment, you need a one-liner to use it in C#:
cmd /c "#for /f "tokens=1* delims=:" %a in ('logman FabricTraces^|find "Root Path"') do #for /f "tokens=*" %r in ("%b") do #echo %r "
Is piping the output and option? If so you could use findstr in windows or grep if it is a Linux base system.
Windows:
logman FabricTraces | findstr Root
Linux:
logman FabricTraces | grep Root
This should show only the Root Path line in the output.
Here is one more solution:
#echo off
for /F "tokens=1,2*" %%A in ('%SystemRoot%\System32\logman.exe FabricTraces 2^>nul') do if "%%A %%B" == "Root Path:" set "RootPath=%%C" & goto RootPath
echo Failed to get root path for FabricTraces.
goto :EOF
:RootPath
echo Root path for FabricTraces is: %RootPath%
rem More commands using environment variable RootPath.
A little bit optimized with using : as delimiter instead of the defaults tab and space:
#echo off
for /F "tokens=1* delims=:" %%A in ('%SystemRoot%\System32\logman.exe FabricTraces 2^>nul') do if "%%A" == "Root Path" set "RootPath=%%B" & goto RootPath
echo Failed to get root path for FabricTraces.
goto :EOF
:RootPath
echo Root path for FabricTraces is: %RootPath%
rem More commands using environment variable RootPath.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
goto /?
if /?
logman /?
rem /?
set /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded logman.exe command line with using a separate command process started in background.

Windows Batch Check Hostname Exists

I want to check if a hostname exists on my PC (ie found in hosts file under C:\Windows\System32\drivers\etc).
Is there a way to find if it exist using a batch command or some other way?
Give a try for this batch file with some extra info :
#echo off
set "SearchString=localhost"
set "LogFile=%userprofile%\Desktop\LogFile.txt"
set "hostspath=%windir%\System32\drivers\etc\hosts"
(
Echo **************************** General info ****************************
Echo Running under: %username% on profile: %userprofile%
Echo Computer name: %computername%
Echo Operating System:
wmic os get caption | findstr /v /r /c:"^$" /c:"^Caption"
Echo Boot Mode:
wmic COMPUTERSYSTEM GET BootupState | find "boot"
Echo Antivirus software installed:
wmic /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get displayName | findstr /v /r /c:"^$" /c:"displayName"
Echo Executed on: %date% # %time%
Echo ********************* Hosts' File Contents with the string "%SearchString%" ************************
)>"%LogFile%"
for /f "delims=" %%a in ('Type "%hostspath%" ^| find /I "%SearchString%"') Do (
echo %%a >> "%LogFile%"
)
Start "" "%LogFile%"
Easier and more robust solution
url.bat:
#echo off
set url=%1
ping -n 1 %url% > nul 2> nul
if "%errorlevel%"=="0" (
echo %url% exists
) else (
echo %url% does not exist
)
Test
> url.bat google.com
google.com exists
> url.bat google.commmmmm
google.commmmmm does not exist
What you possibly can do is pinging the hostname you are looking for and then check for certain strings, that will show you if the hostname could be found or not. Would look like this (I guess):
#echo off
setlocal EnableDelayedExpansion
set /p input= "Hostname"
set hostexists=yes
For /f "tokens=1,2" %%a in ('ping -n 1 !input!') do (
if "x%%a"=="xFOO" if "x%%b"=="xBAR" set hostexists=no
)
If "x!hostexists!"=="xno" (
echo. "Does not exist"
) ELSE (
echo. "Does exist"
Pause
Basic thought is that when you try to ping a hostname that is not available, you will get a specific output from the commandline. Try it yourself: Open the cmd.exe (Hit the Windows-Button +R and type cmd) and in the commandline write ping foobar and wait a bit. You should get a message like: Ping-Request could not find "foobar" [...]. You take the first two words and put them into the code: 1st word to FOO and 2nd to BAR.
The program will look into the output of the ping command and place the first two words (=tokens) in %%a and %%b checking if they are equal to the desired words, marking the host does not exist.
I hope this will help :) Not sure if that is what you wanted :D
Greetings
geisterfurz007

Undefined variable error in a bat file

I tried building a batch file using the commands after searching the site. I am trying to find the number/count of a process running, and then use if to execute another command if the number of such processes is more than 5 at any instance.
When I run the statements line by line in the CMD prompt, it works fine.
However, when I run it through a bat file it gives an error saying- a was unexpected at this time.
Here is the script. Also I am not sure if am using the correct If statement (I did search and use before coming to you, but still just incase):
for /f "tokens=1,*" %a in ('tasklist ^| find /I /C "iexplore.exe" ') do
#set var=%a
echo %var%
if %var% <= 5
::echo "hi"
::end if
Also, have one more syntax to do so:
wmic process where name="iexplore.exe" | find "iexplore.exe" /c
but I am not sure how to assign the output of this command to any variable and go on to compare the value of this command to 5.
You need to use double % for FOR command when used in a batch file.
#echo off
set var=0
for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "explorer.exe" ') do set var=%%a
echo %var%
if %var% leq 5 (
echo less or equal to 5
) else (
echo 5 or more
)

Resources