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():

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?

  • \$\begingroup\$ would not be easier to use paramiko then inventing the wheel? \$\endgroup\$
    – Jakuje
    Commented Jan 22, 2016 at 19:59
  • \$\begingroup\$ @Jakuje ah... well if I've known about this haha.. I think I should refactor my code a bit. \$\endgroup\$ Commented Jan 22, 2016 at 23:27

1 Answer 1


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():
        tunnel_pid = subprocess.check_output(['pgrep', '-f', 'ssh.*27017:localhost:27017'])
    except subprocess.CalledProcessError:
        return 'No Such Process'
    os.kill(tunnel_pid, signal.SIGKILL)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.