int assigned_port;
int local_port=3309;
// Remote host and port
int remote_port=3306;
String remote_host = "<SSH host goes here>";
String login = "<SSH login goes here>";
String password = "<SSH password goes here>";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession(login, remote_host, 22);
session.setPassword(password);
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
} catch (JSchException e) {
System.out.println("JSch:" + e.getMessage());
return;
}
if (assigned_port == 0) {
System.out.println("Port forwarding failed!");
return;
}
现在,我对所有端口转发的东西并不完全熟悉,但是,如果我理解正确的话,代码应该通过SSH转发所有连接到127.0.0.1:3309(或任何assigned_port)的连接服务器。现在我被卡住了。我怎么能通过127.0.0.1:3309发送HttpsURLConnection?我尝试将其定义为HTTP或HTTPS或SOCKS代理,但都不起作用。有人能帮助我吗?
答案 0 :(得分:3)
您发布的代码会将所有流量从127.0.0.1:3309转发到您已连接的SSH服务器上的端口3306。
使用端口转发时,您将侦听地址:端口视为实际目标。因此,如果您需要使用HttpsURLConnection,则可以使用URL
构建它https://127.0.0.1:3309/
显然,您还需要根据您要实现的目标向URL附加路径。我建议修改你的代码以使用更多的标准HTTP端口,首先尝试使用HTTP,然后一旦尝试移动到HTTPS
int local_port=8080; // Remote host and port int remote_port=80;
上面的网址是
http://127.0.0.1:8080
您始终可以通过将URL粘贴到浏览器来测试该URL。
使用HTTPS可能遇到的问题之一是证书验证,因此我建议首先测试普通HTTP以证明您的代码正常运行。