【发布时间】:2014-05-24 02:00:52
【问题描述】:
使用http://www.jcraft.com/jsch/examples/StreamForwarding.java.html 处的代码,我尝试创建使用JSch 连接到SSH 服务器的代码,然后使用它连接到Web 中的服务器并将HTTP(s) 请求传递给服务器,基本上使用 SSH 服务器作为代理。这是我所拥有的:
//SSH server and credentials
String host = "00.000.000.00";
String user = "login";
String password = "password";
int port = 22;
//The host I want to send HTTP requests to - the remote host
String remoteHost = "test.com";
int remotePort = 80;
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig(config);
session.connect();
Channel channel = session.getStreamForwarder(remoteHost, remotePort);
//The GET request
String cmd = "GET /foo/foo HTTP/1.0\r\n\r\n";
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
channel.connect(10000);
byte[] bytes = cmd.getBytes();
InputStream is = new ByteArrayInputStream(cmd.getBytes("UTF-8"));
int numRead;
while ((numRead = is.read(bytes)) >= 0)
out.write(bytes, 0, numRead);
out.flush();
channel.disconnect();
session.disconnect();
System.out.println("Request supposed to have been sent");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
for (String line; (line = reader.readLine()) != null;){
System.out.println(line);
}
} catch (java.io.IOException exc) {
System.out.println(exc.toString());
}
} catch (Exception e){
e.printStackTrace();
}
这在理论上听起来不错,但实际上它不起作用。我认为我可能可以实现本地端口转发以使其工作,但我不明白如何。有人可以帮帮我吗?
【问题讨论】:
-
你说“它不起作用”。它以什么方式不起作用?您收到错误消息吗?例外?还有什么?失败时正在执行程序的哪一行?
-
连接不上。就如此容易。 test.com/foo/foo 上有一个记录器,它没有记录脚本的访问。
标签: java http ssh jsch channel