简体   繁体   中英

Python - How to close a port left open?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM