19

I want a script which kills the instance(s) of ssh which are run with the -D argument (setting up a local proxy).

Manually, I do ps -A | grep -i ssh, look for the instance(s) with -D, and kill -9 {id} each one.

But what does that look like in bash script form?

(I am on Mac OS X but will install any necessary commands via port)

Ricket
  • 702
  • 3
  • 8
  • 14

3 Answers3

28

Run pgrep -f "ssh.*-D" and see if that returns the correct process ID. If it does, simply change pgrep to pkill and keep the same options and pattern

Also, you shouldn't use kill -9 aka SIGKILL unless absolutely necessary because programs can't trap SIGKILL to clean up after themselves before they exit. I only use kill -9 after first trying -1 -2 and -3.

SiegeX
  • 8,859
2

Also,

kill `pgrep -f "ssh.*-D"`
Barun
  • 2,376
0

You can leverage the proc file system to gather the information. For example:

for proc in $(grep -irl "ssh.*-D" /proc/*/cmdline | grep -v "self"); do if [ -f $proc ]; then cat $proc && echo ""; fi; done

It's not perfect, you'll want a more exclusive regex (especially if you are killing processes) but echo $proc | awk -F'/' '{ print $3 }' will show you the PID of the process(es).

Tok
  • 10,744