Class: Net::SSH::Service::Forward

Inherits:
Object
  • Object
show all
Defined in:
lib/net/ssh/socks.rb

Instance Method Summary collapse

Instance Method Details

#socks(*args) ⇒ Object

Starts listening for connections on the local host, and forwards them to the specified remote host/port via the SSH connection. This method accepts either one or two arguments. When two arguments are given, they are:

  • the local address to bind to

  • the local port to listen on

If one argument is given, it is as if the local bind address is “127.0.0.1”, and the rest are applied as above.

ssh.forward.socks(8080)
ssh.forward.socks("0.0.0.0", 8080)


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/net/ssh/socks.rb', line 112

def socks(*args)
  if args.length < 1 || args.length > 2
    raise ArgumentError, "expected 1 or 2 parameters, got #{args.length}"
  end

  bind_address = "127.0.0.1"
  bind_address = args.shift if args.first.is_a?(String) && args.first =~ /\D/
  local_port   = args.shift.to_i
  info { "socks on #{bind_address} port #{local_port}" }

  socks_server = TCPServer.new(bind_address, local_port)
  session.listen_to(socks_server) do |server|
    client = server.accept

    socks = Net::SSH::Socks.new(client)
    remote_host, remote_port = socks.client_handshake
    info { "connection requested on #{remote_host} port #{remote_port}" }

    channel = session.open_channel("direct-tcpip", :string, remote_host, :long, remote_port, :string, bind_address, :long, local_port) do |channel|
      info { "direct channel established" }
      prepare_client(client, channel, :local)
    end

    channel.on_open_failed do |ch, code, description|
      error { "could not establish direct channel: #{description} (#{code})" }
      client.close
    end
  end

  session.on_close do
    debug { "cleaning up socks server" }
    socks_server.close
  end
end