|
- #!/bin/bash
- if [[ $# -ne 1 || "$1" == '-h' || "$1" == '--help' ]]
- then
- echo "Usage: kill-connections PID" >&2
- exit 1
- fi
-
- if ! command -v tcp-closer &>/dev/null
- then
- echo "Error: could not find tcp-closer" >&2
- exit 1
- fi
-
- declare -i pid="$1"
- if ! kill -0 ${pid} &>/dev/null
- then
- echo "Error: no process ${pid}" >&2
- exit 1
- fi
-
- kill -STOP ${pid}
-
- echo "Open connections:" >&2
- lsof -a -p ${pid} -i TCP -n >&2
- echo >&2
-
- readarray -t v4sports < <(lsof -a -p ${pid} -i4 -i TCP -n -F nP0 | grep -Pao '\x00n\d{1,3}(\.\d{1,3}){3}:\K\d+' | sed 's,^,-s ,')
- if [[ ${#v4sports[@]} -gt 0 ]]
- then
- echo "Killing IPv4 connections" >&2
- #TODO This may also kill connections we want to keep. tcp-closer does not allow specifying the full (src, sport, dst, dport) tuple...
- for ((i=0; i<${#v4sports[@]}; i+=64))
- do
- tcp-closer -4 ${v4sports[@]:${i}:64}
- done
- echo >&2
- fi
- readarray -t v6sports < <(lsof -a -p ${pid} -i6 -i TCP -n -F nP0 | grep -Pao '\x00n\[[^\]]+\]:\K\d+' | sed 's,^,-s ,')
- if [[ ${#v6sports[@]} -gt 0 ]]
- then
- echo "Killing IPv6 connections" >&2
- for ((i=0; i<${#v6sports[@]}; i+=64))
- do
- tcp-closer -6 ${v6sports[@]:${i}:64}
- done
- echo >&2
- fi
-
- sleep 1
-
- echo "Open connections:" >&2
- lsof -a -p ${pid} -i TCP -n >&2
-
- kill -CONT ${pid}
|