Created
May 11, 2018 21:06
-
-
Save ArthurYidi/a1d305b13b3fc433e6904e753e6df040 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from subprocess import check_output, CalledProcessError | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("port", help="Port Number") | |
parser.add_argument("-n", "--dry-run", action="store_false", help="run without killing processes") | |
args = parser.parse_args() | |
# lsof | |
# -t show process only | |
# -i match prtocol and port | |
# -s protocol state | |
# -P -n just show port number | |
# lsof -t -iTCP:3449 -sTCP:LISTEN | |
try: | |
pids = check_output(["lsof", "-t", "-i:" + args.port, "-sTCP:LISTEN"]) | |
except CalledProcessError as error: | |
print("No process found using port: " + args.port) | |
exit() | |
pids = pids.decode('utf-8').strip().split('\n') | |
def pidinfo(pid): | |
return check_output(["lsappinfo", "info " + pid]) | |
def pidname(pid): | |
return check_output(["ps", "-c", '-p {}'.format(pid), '-o comm=']).decode('utf-8').strip() | |
def pidpath(pid): | |
return check_output(["ps", '-p {}'.format(pid), '-o comm=']).decode('utf-8').strip() | |
for pid in pids: | |
if not args.dry_run: | |
print('Would Kill: {} {} "{}"'.format(pidname(pid), pid, pidpath(pid))) | |
continue | |
error = check_output(["kill", pid]) | |
if error: | |
print(error) | |
continue | |
print('Killed: {} {} "{}"'.format(pidname(pid), pid, pidpath(pid))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment