java 建立ssh隧道_通过JSch的SSH隧道

我的目的是连接到位于防火墙后面的服务器(主机)。我可以通过连接到网络中的另一台服务器(隧道)然后通过SSH到该服务器来访问此服务器。但是,我无法通过JSch实现相同的方案。

我无法为此编写以下代码。如果我在这里做任何愚蠢的事情,请告诉我。

public class JschExecutor {

public static void main(String[] args){

JschExecutor t=new JschExecutor();

try{

t.go();

} catch(Exception ex){

ex.printStackTrace();

}

}

public void go() throws Exception{

StringBuilder outputBuffer = new StringBuilder();

String host="xxx.xxx.xxx.xxx"; // The host to be connected finally

String user="user";

String password="passwrd";

int port=22;

String tunnelRemoteHost="xx.xx.xx.xx"; // The host from where the tunnel is created

JSch jsch=new JSch();

Session session=jsch.getSession(user, host, port);

session.setPassword(password);

localUserInfo lui=new localUserInfo();

session.setUserInfo(lui);

session.setConfig("StrictHostKeyChecking", "no");

ProxySOCKS5 proxyTunnel = new ProxySOCKS5(tunnelRemoteHost, 22);

proxyTunnel.setUserPasswd(user, password);

session.setProxy(proxyTunnel);

session.connect(30000);

Channel channel=session.openChannel("exec");

((ChannelExec)channel).setCommand("hostname");

channel.setInputStream(null);

((ChannelExec)channel).setErrStream(System.err);

InputStream in=channel.getInputStream();

BufferedReader ebr = new BufferedReader(new InputStreamReader(in));

channel.connect();

while (true) {

byte[] tmpArray=new byte[1024];

while(in.available()>0){

int i=in.read(tmpArray, 0, 1024);

if(i<0)break;

outputBuffer.append(new String(tmpArray, 0, i)).append("\n");

}

if(channel.isClosed()){

System.out.println("exit-status: "+channel.getExitStatus());

break;

}

}

ebr.close();

channel.disconnect();

session.disconnect();

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

}

}

上面的代码session.connect(30000);在行中给出了以下异常。

com.jcraft.jsch.JSchException: ProxySOCKS5: com.jcraft.jsch.JSchException: fail in SOCKS5 proxy

at com.jcraft.jsch.ProxySOCKS5.connect(ProxySOCKS5.java:317)

at com.jcraft.jsch.Session.connect(Session.java:231)

at com.ukris.main.JschExecutor.go(JschExecutor.java:50)

at com.ukris.main.JschExecutor.main(JschExecutor.java:19)

Caused by: com.jcraft.jsch.JSchException: fail in SOCKS5 proxy

at com.jcraft.jsch.ProxySOCKS5.connect(ProxySOCKS5.java:200)

... 3 more

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值