Created
October 20, 2012 23:56
-
-
Save sgrankin/3925289 to your computer and use it in GitHub Desktop.
SSH local/remote proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'resolv' | |
require 'optparse' | |
require 'ostruct' | |
require 'pp' | |
$opts = OpenStruct.new | |
parser = OptionParser.new do |parser| | |
parser.banner = <<-EOS | |
#$0: | |
SSH into a host via a proxy, but only if both have an IP address in common. | |
This is typical of hosts hidden behind a NAT, and allows efficient connections when inside the NAT network. | |
Example for .ssh/config | |
ProxyCommand ~/.ssh/#$0 <proxy.example.com> %h %p | |
Usage: | |
#$0 [options] proxy-host host port | |
EOS | |
parser.on("-v", "--[no-]verbose", "Run verbosely"){|v| $opts.verbose = v} | |
end | |
parser.parse! | |
proxy_host = ARGV.shift | |
host = ARGV.shift | |
port = ARGV.shift || 22 | |
unless host | |
puts parser | |
exit 1 | |
end | |
dns = Resolv::DNS.new | |
$stderr << "#$0: ... #{proxy_host} ... #{host}:#{port}\n" if $opts.verbose | |
proxy_addrs = dns.getaddresses(proxy_host) | |
host_addrs = dns.getaddresses(host) | |
if (proxy_addrs & host_addrs).empty? or proxy_host == host | |
# proxy and host have the different addresses -- contact host directly | |
cmd = "nc #{host} #{port}" | |
else | |
# proxy and host have the same address -- we're likely outside the network, so proxy in | |
cmd = "ssh -W #{host}:#{port} #{proxy_host} 2> /dev/null" | |
end | |
$stderr << "#$0: exec #{cmd}\n" if $opts.verbose | |
exec cmd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment