HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Killing a tunnel and establishing a tunnel through SSH

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
establishingkillingtunnelthroughandssh

Problem

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?

Solution

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)

Code Snippets

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

Context

StackExchange Code Review Q#117624, answer score: 3

Revisions (0)

No revisions yet.