1

I have a process which at times is opening a port and then not closing it (I'm on Windows 10).

What is the best way to close this via Python? The port number is 1300 and will not change.

I know this can be done manually via command line by killing the PID, however I would like to keep it all in one easy to use batch file.

flec8
  • 37
  • 1
  • 8
  • If the process that's keeping the port open is still running, there's nothing you can do externally other than killing the process. – jasonharper Aug 09 '17 at 18:11
  • @jasonharper that doesn't seem to be the case—the free [CurrPorts](https://www.nirsoft.net/utils/cports.html) utility says that it can close specific connections not belonging to itself. See the section "Closing a Connection From Command-Line" of the linked page. – Alex Peters Jan 28 '22 at 06:40

1 Answers1

2

You can use the psutil module.

from psutil import process_iter
from signal import SIGKILL

for proc in process_iter():
    for conns in proc.get_connections(kind='inet'):
        if conns.laddr[1] == 1300:
            proc.send_signal(SIGKILL) 
            continue

Otherwise, you should just call kill from subprocess.

modesitt
  • 7,052
  • 2
  • 34
  • 64