Link to home
Start Free TrialLog in
Avatar of Rajat Sehgal
Rajat SehgalFlag for India

asked on

Kill TCP IP & Port

Hi Experts,
How to grep connected tcp IP & Port connection then forcefully kill using batch.

example;-
netstat -a output is

Active Connections

  Proto    Local Address                        Foreign Address                State
  TCP       192.168.1.101:49366            192.168.1.55:65000          ESTABLISHED
  TCP       192.168.1.101:49475            192.168.1.55:64000          ESTABLISHED
  TCP       192.168.1.101:49384            192.168.1.55:63500          ESTABLISHED
  TCP       192.168.1.101:49396            192.168.1.55:22                 ESTABLISHED

Need to forcefully kill all TCP connection which is connected with 192.168.1.55
Avatar of Predrag Jovic
Predrag Jovic
Flag of Poland image

netstat -ano
output:
Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:135            0.0.0.0:0           ESTABLISHED      1296

Open in new window

taskkill /f /im 1296

It may require elevated privileges.
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rajat Sehgal

ASKER

Is there any idea with batch, which can i use easily ?
All you need to put into a .cmd or .bat file is the line as I have shown (the very last line). Put that and CurPorts into the same folder, and run the batch file. Nothing more to do.
If you're trying to kill all connections from the command line then simply run

cports /close * * * *

Open in new window


If you want to process each connection for some reason, then you could use the following as a template:

[TCPKill.bat]
@echo off
setlocal enabledelayedexpansion
for /f "tokens=2,3,5" %%a in ('netstat -ano -p tcp^|findstr ESTABLISHED') do (
	set str=%%a %%b %%c
	set str=!str::= !
	if exist cports.exe (
		echo running cports.exe /close !str!
		cports.exe /close !str!
	) else (
		echo cports.exe not found.
		goto :eof
	)
	set str=
)

Open in new window


Which is good for IPv4 connections.  Bear in mind a given process may simply try to reconnect once disconnected.
Helpful