Wednesday, April 26, 2017

Batch Script to Find Process Connecting to IP Address

Recently I had to find what process on a remote machine was connecting to a certain IP address, to determine if it was malicious or not, using only the command line.  This is how I did it, by using a batch file to watch netstat for the connection.  If it sees it, it'll write the line from netstat into a file.  If that file ever changes size, it'll also run tasklist to get the process name from the PID.  There's probably nicer ways of doing it, but this was slapped together quickly to get the results we needed.

:loop
set file="netstat_hits.txt"
netstat -ano | findstr 10.1.2.3 >> netstat_hits.txt
netstat -ano | findstr ":80 " >> netstat_hits.txt
FOR /F "usebackq" %%A IN ('%file%') DO set size=%%~zA
IF %size% NEQ 1 goto tasker
ping 127.0.0.1
goto loop

:tasker
tasklist >> netstat_hits.txt
goto loop

The file started out as one byte (I just put an "a" in it).  If the netstat | findstr >> file combo worked, it would trigger the :tasker call to write the tasklist into the same file.  Then I just periodically checked to see if the file was ever more than 1 byte big, and ctrl-c'd the batch script.

If someone knows of a better way of doing it, I'm all ears.

No comments:

Post a Comment