# Killing a tunnel and establishing a tunnel through SSH

I have two functions right now:

TUNNEL_COMMAND = "ssh -L 27017:localhost:27017 username@ip -f -N"

def kill_tunnel():
p = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if TUNNEL_COMMAND in line:
pid = int(line.split()[1])
print "killing pid", pid
os.kill(pid, signal.SIGKILL)

def connect_tunnel():
subprocess.Popen(TUNNEL_COMMAND)


connect_tunnel() establishes the connection, which I am ok with, but kill_tunnel() looks very ugly. Is there a better way to find the PID of a process based off the command?

• would not be easier to use paramiko then inventing the wheel? – Jakuje Jan 22 '16 at 19:59
• @Jakuje ah... well if I've known about this haha.. I think I should refactor my code a bit. – Stupid.Fat.Cat Jan 22 '16 at 23:27

How about using pgrep with the -f option to match the whole command line so that we can match the desired process precisely?

For example, in you case something like:

pgrep -f 'ssh.*27017:localhost:27017'


might give the accurate PID. If you desire, you can modify it to make it more robust.

Implementing this in Python:

import subprocess
import os
import signal

def kill_tunnel():
try:
tunnel_pid = subprocess.check_output(['pgrep', '-f', 'ssh.*27017:localhost:27017'])
except subprocess.CalledProcessError:
return 'No Such Process'
os.kill(tunnel_pid, signal.SIGKILL)