通过安全的ssh连接进行TCP连接

时间:2013-03-04 20:46:18

标签: ssh jsch channel

我正在尝试使用JSCH连接到远程服务器,然后从该服务器通过tcp / ip端口打开类似会话的telnet。假设连接到服务器A,并且一旦连接,就通过另一个端口向服务器B发出tcp连接。在我的网络服务器日志中,我看到了GET /已记录,但没有像我期望的那样获得GET / foo。我在这里缺少什么? (我不需要使用端口转发,因为我连接的系统可以访问远程端口)

package com.tekmor;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
.
.

public class Siranga {

     public static void main(String[] args){
        Siranga t=new Siranga();
           try{
               t.go();
           } catch(Exception ex){
               ex.printStackTrace();
        }
    }
    public void go() throws Exception{
        String host="hostXXX.com";
        String user="USER";
        String password="PASS";
        int port=22;

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");      

        String remoteHost="hostYYY.com";
        int remotePort=80;


       try { 
        JSch jsch=new JSch();
        Session session=jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        Channel channel=session.openChannel("direct-tcpip");  


        ((ChannelDirectTCPIP)channel).setHost(remoteHost);
        ((ChannelDirectTCPIP)channel).setPort(remotePort);

        String cmd = "GET /foo";

        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);
              System.out.println(numRead);
        }

        out.flush();



        channel.disconnect();
        session.disconnect();

        System.out.println("foo");

       }
       catch (Exception e){
           e.printStackTrace();

       }

    }
}

1 个答案:

答案 0 :(得分:0)

再次阅读HTTP specification。请求标头应以空行结束。因此,假设您没有更多标题行,您至少应该在结尾处使用换行符。 (此处的换行符表示CRLF组合。)

此外,请求行应包含URL之后的HTTP版本标识符。

请尝试对您的计划进行此更改:

String command = "GET /foo HTTP/1.0\r\n\r\n";

作为提示:您可以使用setInputStream method,而不是手动将数据从ByteArrayInputStream传递到通道的输出流。另外,不要忘记从频道的输入流中读取结果。

相关问题