Skip to content

Instantly share code, notes, and snippets.

@jossef
Last active July 6, 2023 08:29
Show Gist options
  • Save jossef/593ade757881bb7ddfe0 to your computer and use it in GitHub Desktop.
Save jossef/593ade757881bb7ddfe0 to your computer and use it in GitHub Desktop.
python kill process by port
#!/usr/bin/env python
import subprocess
import sys
import re
import os
def get_pids(port):
command = "sudo lsof -i :%s | awk '{print $2}'" % port
pids = subprocess.check_output(command, shell=True)
pids = pids.strip()
if pids:
pids = re.sub(' +', ' ', pids)
for pid in pids.split('\n'):
try:
yield int(pid)
except:
pass
if __name__ == '__main__':
args = sys.argv[1:]
if not len(args):
print 'gimmi port'
sys.exit(1)
port = args[0]
pids = set(get_pids(port))
command = 'sudo kill -9 {}'.format(' '.join([str(pid) for pid in pids]))
os.system(command)
@yusuf8ahmed
Copy link

"gimmi port " lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment