如何将设备的流量转发到ssh隧道

时间:2019-06-26 10:26:39

标签: android vpn ssh-tunnel

我在美国有一台服务器,上面装有ssh。在Windows中,我使用putty.exe创建ssh隧道,然后手动设置应用程序的代理以将流量转发到ssh隧道端口,以将其转发到服务器。现在我想在android上执行此操作。我有以下代码使用JSch与ssh服务器建立连接。我不知道我是否使用正确的方法,也不知道如何将整个设备流量转发到setPortForwardingL设置的ssh隧道。我从某个网站复制了此代码,并认为本地端口2233正在通过ssh隧道侦听转发到服务器。如果您有任何帮助,请帮助我。我认为需要VPN。

 public void go() throws Exception{

    StringBuilder outputBuffer = new StringBuilder();
    String host="My US server IP"; // First level target
    String user="ssh user";
    String password="ssh password";
    String tunnelRemoteHost="???"; // The host of the second target
    String secondPassword="pass";
    int port=22;


    JSch jsch=new JSch();
    Session session=jsch.getSession(user, host, port);
    session.setPassword(password);
    localUserInfo lui=new localUserInfo();
    session.setUserInfo((UserInfo) lui);
    session.setConfig("StrictHostKeyChecking", "no");
    // create port from 2233 on local system to port 22 on tunnelRemoteHost
    session.setPortForwardingL(2233, tunnelRemoteHost, 22);
    session.connect();
    session.openChannel("direct-tcpip");

    // create a session connected to port 2233 on the local host.
    Session secondSession = jsch.getSession(user, "localhost", 2233);
    secondSession.setPassword(secondPassword);
    secondSession.setUserInfo(lui);
    secondSession.setConfig("StrictHostKeyChecking", "no");

    secondSession.connect(); // now we're connected to the secondary system
    Channel channel=secondSession.openChannel("exec");
    ((ChannelExec)channel).setCommand("hostname");

    channel.setInputStream(null);

    InputStream stdout=channel.getInputStream();

    channel.connect();
    Log.i("hixnal","connected");
    while (true) {
        byte[] tmpArray=new byte[1024];
        while(stdout.available() > 0){
            int i=stdout.read(tmpArray, 0, 1024);
            if(i<0)break;
            outputBuffer.append(new String(tmpArray, 0, i));
        }
        if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
        }
    }
    stdout.close();

    channel.disconnect();

    secondSession.disconnect();
    session.disconnect();

    System.out.print(outputBuffer.toString());
}

class localUserInfo implements UserInfo{
    String passwd;
    public String getPassword(){ return passwd; }
    public boolean promptYesNo(String str){return true;}
    public String getPassphrase(){ return null; }
    public boolean promptPassphrase(String message){return true; }
    public boolean promptPassword(String message){return true;}
    public void showMessage(String message){}
}

0 个答案:

没有答案