Sample code for 30+ languages & platforms
Java

SSH Tunnel Through an Outbound SOCKS Proxy

See more SSH Tunnel Examples

Demonstrates reaching the SSH server through an outbound SOCKS proxy using the SocksVersion, SocksHostname, SocksPort, SocksUsername, and SocksPassword properties.

Background: This is the reverse direction from dynamic forwarding: here a SOCKS proxy is used to reach the SSH server, for networks where outbound connections must pass through one. SocksVersion is the switch — 0 means no SOCKS, while 4 or 5 selects the protocol. SOCKS5 supports username/password authentication and remote DNS; SOCKS4 supports only a username.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates reaching the SSH server through an outbound SOCKS proxy using the SshTunnel
    //  properties SocksVersion, SocksHostname, SocksPort, SocksUsername, and SocksPassword.

    CkSshTunnel tunnel = new CkSshTunnel();

    //  Set SocksVersion to 4 or 5 to route the outbound connection to the SSH server through a SOCKS
    //  proxy.  A value of 0 (the default) means no SOCKS proxy.
    tunnel.put_SocksVersion(5);
    tunnel.put_SocksHostname("socks.example.com");
    tunnel.put_SocksPort(1080);

    //  SOCKS4 supports only a username; SOCKS5 supports username and password.
    tunnel.put_SocksUsername("myProxyLogin");
    tunnel.put_SocksPassword("myProxyPassword");

    tunnel.put_DestHostname("db.internal.example.com");
    tunnel.put_DestPort(5432);

    //  Connect to the SSH server through the SOCKS proxy configured above.
    int sshPort = 22;
    success = tunnel.Connect("ssh.example.com",sshPort);
    if (success == false) {
        System.out.println(tunnel.lastErrorText());
        return;
        }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    String password = "mySshPassword";

    success = tunnel.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        System.out.println(tunnel.lastErrorText());
        return;
        }

    int listenPort = 1080;
    success = tunnel.BeginAccepting(listenPort);
    if (success == false) {
        System.out.println(tunnel.lastErrorText());
        return;
        }

    System.out.println("Tunnel established through the SOCKS proxy.");

    boolean waitForThreadExit = true;
    success = tunnel.CloseTunnel(waitForThreadExit);
    if (success == false) {
        System.out.println(tunnel.lastErrorText());
        return;
        }
  }
}