Skip to content

Instantly share code, notes, and snippets.

@Hiestaa
Created October 6, 2017 16:15
Show Gist options
  • Save Hiestaa/f74b51321ca58a69f0ffbc654f5b50d0 to your computer and use it in GitHub Desktop.
Save Hiestaa/f74b51321ca58a69f0ffbc654f5b50d0 to your computer and use it in GitHub Desktop.
Got a pesky process listening on a specific port and wanna get rid of it? Run `python killListener.py [port]`. Additional `name` argument can be given to filter out processes going to get killed by name.
import subprocess
import sys
if len(sys.argv) > 1:
port = sys.argv[1]
else:
port = '3996'
if (len(sys.argv) > 2):
name = sys.argv[2]
else:
name = None
if any(v in ['-h', '--help'] for v in sys.argv):
print "Usage: python killListener.py [port=3996] [name]"
exit(0)
try:
print("> lsof -i tcp:%s" % port)
res = subprocess.check_output('lsof -i tcp:%s' % port, shell=True)
print(res)
except: # returns a non-0 exit code it no result
print("> # No process listening on port %s. Terminating." % port)
exit(0)
res = res.split('\n')
if len(res) < 2:
print("> # No process listening on port %s. Terminating." % port)
exit(0)
for line in res:
line = line.split()
if len(line) < 2:
continue
if name is not None and line[0] != name:
print("> # ignoring process %s pid=%s (not '%s')"
% (line[0], line[1], name))
continue
pid = line[1]
print('> kill -kill %s' % (pid))
res2 = subprocess.check_output('kill -kill %s' % (pid), shell=True)
print(res2)
print("Success!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment