Skip to content

Instantly share code, notes, and snippets.

@Geekfish
Last active December 25, 2015 21:29
Show Gist options
  • Save Geekfish/30a3c07b6fee31b0e2bf to your computer and use it in GitHub Desktop.
Save Geekfish/30a3c07b6fee31b0e2bf to your computer and use it in GitHub Desktop.
Create an ssh tunnel to a postgres db server
#!/usr/bin/perl
# PostgreSQL Tunnel Tool for Mac OS X and Linux
# Copyright (c) 2010 Linode, LLC
# Author: Philip C. Paradis <pparadis@linode.com>
# Usage: postgresql-tunnel.pl [start|stop]
# Access a PostgreSQL database server via an SSH tunnel.
$local_ip = "127.0.0.1";
$local_port = "5433";
$remote_port = "5432";
$remote_user = "my_username";
$remote_host = "myhost.example.com";
$a = shift;
$a =~ s/^\s+//;
$a =~ s/\s+$//;
$pid=`ps ax|grep ssh|grep $local_port|grep $remote_port`;
$pid =~ s/^\s+//;
@pids = split(/\n/,$pid);
foreach $pid (@pids)
{
if ($pid =~ /ps ax/) { next; }
split(/ /,$pid);
}
if (lc($a) eq "start")
{
if ($_[0]) { print "Tunnel already running.\n"; exit 1; }
else
{
system "ssh -f -L $local_port:$local_ip:$remote_port $remote_user\@$remote_host -N";
exit 0;
}
}
elsif (lc($a) eq "stop")
{
if ($_[0]) { kill 9,$_[0]; exit 0; }
else { exit 1; }
}
else
{
print "Usage: postgresql-tunnel.pl [start|stop]\n";
exit 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment