Skip to content
Advertisement

Kill program listening to a given port

Before the main code execution starts, I want to check if a particular port is open or not.. and if it is.. then close the port so that code can start “cleanly”.

So I google online and found the code here: http://www.paulwhippconsulting.com.au/tips/63-finding-and-killing-processes-on-ports

But just pasting the code from there:

import os
import subprocess
import re

ports = ['1234','5678','9101']


popen = subprocess.Popen(['netstat', '-lpn'],
                         shell=False,
                         stdout=subprocess.PIPE)
(data, err) = popen.communicate()

pattern = "^tcp.*((?:{0})).* (?P[0-9]*)/.*$"
pattern = pattern.format(')|(?:'.join(ports))
prog = re.compile(pattern) #<---- error line
for line in data.split('n'):
    match = re.match(prog, line)
    if match:
        pid = match.group('pid')
        subprocess.Popen(['kill', '-9', pid])

But it throws an error.

 raise error, v # invalid expression
sre_constants.error: unknown specifier: ?P[

Advertisement

Answer

The fellow who posted that snippet forgot to HTML-escape his code! The correct code is as follows:

import os
import subprocess
import re

ports = ['1234','5678','9101']


popen = subprocess.Popen(['netstat', '-lpn'],
                         shell=False,
                         stdout=subprocess.PIPE)
(data, err) = popen.communicate()

pattern = "^tcp.*((?:{0})).* (?P<pid>[0-9]*)/.*$"
pattern = pattern.format(')|(?:'.join(ports))
prog = re.compile(pattern)
for line in data.split('n'):
    match = re.match(prog, line)
    if match:
        pid = match.group('pid')
        subprocess.Popen(['kill', '-9', pid])

Note that <pid> follows the ?P.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement