Killing a tunnel and establishing a tunnel through SSH
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)