PryroTech
PryroTech

Reputation: 504

Trying to make a Batch File that detects unauthorized connections via netstat

I have a little bit of a dilemma going on right now. You see I am trying to make a batch app that will detect unknown connections from saved connections in a text file. Somehow I need the app to compare the netstat results to the one's in the text file. Here's what I tried:

if %netstat -b 5% equ c:\list.txt goto :win
else goto :fail

Now I did try to find a solution but to no avail. Maybe I am doing something wrong? Or is there another way of doing this? I want the netstat command to compare the results to what was logged in the text file. Please help me!

Upvotes: 0

Views: 350

Answers (1)

FloatingKiwi
FloatingKiwi

Reputation: 4506

The following command will do what you're after.

for /f "tokens=3" %%f in ('netstat -b 5') do (
    findstr /c:"%%f" c:\list.txt && (
        echo Allowed %%f 
    ) || (
        echo Disallowed %%f
    )
)

This will iterate over each line of output from netstat -b 5. (Note this is really slow so for testing I redirected the output to netstat.output and then just loaded the file instead).

Description:

  • For /F - iterate over each line that comings from the command / file in brackets.
  • tokens=3 - get me the 3rd token (the remote address)
  • %%f - name of the variable
  • 'netstat -b 5' or netstat.output - the source of the lines to iterate over
  • do - the command to run

Then we launch findstr and tell it to look for a string %%f in the file c:\list.txt. If it succeeds the && command will run echoing this address. Otherwise if the string is not found the || command will run

Upvotes: 1

Related Questions