SOCKSjsch上的代理设置允许您连接到远程端上 正在运行的 代理服务器。一个
sshd在远程端将 不
被视为一个
SOCKS代理。您需要做的是建立一个本地端口,该本地端口转发到您要隧道连接到的计算机上的ssh端口,然后使用api建立与此系统的辅助ssh连接。
我以您的示例为例,并对其进行了略微重写以实现此目的:
import com.jcraft.jsch.*;import java.io.*;public class JschExecutor2 { public static void main(String[] args){ JschExecutor2 t=new JschExecutor2(); try{ t.go(); } catch(Exception ex){ ex.printStackTrace(); } } public void go() throws Exception{ StringBuilder outputBuffer = new StringBuilder(); String host="firstsystem"; // First level target String user="username"; String password="firstlevelpassword"; String tunnelRemoteHost="secondlevelhost"; // The host of the second target String secondPassword="targetsystempassword"; int port=22; 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"); // 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(); 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){} }}
这段代码的作用是创建一个本地端口,将其转发到目标系统上的ssh端口,然后通过它进行连接。hostname命令的运行表明它确实在转发的系统上运行。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)