其他Java程序员。最近,我面临着一个有趣的任务-创建使用SSH隧道作为浏览网页(通过HTTPS)的代理的软件。在阅读了有关JSCH的一些文档(http://www.jcraft.com/jsch/,一个Java SSH隧道库)后,所有这些文档都以数据库连接为例,我决定自己尝试一下。这是我从http://kahimyang.info/kauswagan/code-blogs/1337/ssh-tunneling-with-java-a-database-connection-example复制的连接代码
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代理,但均无效。有谁能够帮助我?
您发布的代码会将所有流量从127.0.0.1:3309转发到您连接到的SSH服务器上的端口3306。
使用端口转发时,您将侦听地址:端口视为实际目的地。因此,如果您需要使用HttpsURLConnection,则可以使用以下网址构建它:
https://127.0.0.1:3309/
显然,您还需要根据要实现的目标在URL上附加路径。我建议您修改代码以使用更多标准HTTP端口,先尝试使用HTTP,然后在可行的情况下移至HTTPS
int local_port=8080; // Remote host and port int remote_port=80;
上面的URL将是
http://127.0.0.1:8080
您始终可以通过将URL粘贴到浏览器中来测试URL。
使用HTTPS可能会遇到的问题之一是证书验证,所以这就是为什么我建议首先测试纯HTTP来证明您的代码可以正常工作的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句