通过 JSch 进行 SSH 隧道
2022-09-04 21:38:45
我的目标是连接到防火墙后面的服务器(主机)。我能够通过连接到网络中的另一台服务器(隧道),然后通过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