Skip to content

Instantly share code, notes, and snippets.

@geeksunny
Created October 14, 2013 15:32
Show Gist options
  • Save geeksunny/6977551 to your computer and use it in GitHub Desktop.
Save geeksunny/6977551 to your computer and use it in GitHub Desktop.
A quick'n'dirty Python script for starting / stopping a port-forwarded SSH tunnel.
#!/usr/bin/python
import os # For running system commands.
import argparse # For command-line argument parsing.
## Configuration ##
__command__ = "ssh -L [LOCAL PORT]:127.0.0.1:[REMOTE PORT] [USER]@[REMOTE HOST] -f -N"
###################
## TODO ##
# * Build out the argparse system to parameterize the connection details.
# * Implement a nickname / bookmark feature (w/ wizard?).
##########
### Parsing command arguments
parser = argparse.ArgumentParser(description='Start & stop a local SSH Tunnel.')
parser.add_argument('-s', '--start', action='store_const', const=True, required=False, default=False,
help='Start the tunnel')
parser.add_argument('-k', '--kill', action='store_const', const=True, required=False, default=False,
help='Kill the tunnel')
# Parse argument values into the 'args' namespace object.
args = parser.parse_args()
if args.start is True:
os.system(__command__)
elif args.kill is True:
os.system("kill `ps -A|awk '/"+__command__+"/{print $1}'`")
else:
print "Please use the -s or -k flags to control your tunnel."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment