Access other nodes through a jumper using the JSCH framework

A set of code for remotely accessing ssh has been developed. Recently, there is a need for a jumper to access the target...

A set of code for remotely accessing ssh has been developed. Recently, there is a need for a jumper to access the target service.After searching the web for half a day, I didn't find a good example, so I browsed the API of JSCH myself.But look in the clouds.Imagine if port forwarding works by mapping the target node ip:port to localhost:port and sending a message through localhost:port to reach the target node?

With this inference, the code that preceded the next one was transformed.

The original code connects the target node server through jsch, let alone say, Baidu itself, there are many on the Internet.

Following is the code for the modification:

1 /** 2 * Get Connections 3 * @param ip Jump host 4 * @param userName Jump User Name 5 * @param pwd Skip Secret Code 6 * @param port Jump Port 7 * @return ChannelSftp Return value 8 * @throws JSchException Connection exception 9 */ 10 public static ChannelSftp connect(String ip, String userName, String pwd, int port) throws JSchException 11 { 12 if (port <= 0) 13 { 14 port = PORT; 15 } 16 Session sshSession = null; 17 JSch jsch = new JSch(); 18 sshSession = jsch.getSession(userName, ip, port); 19 20 sshSession.setPassword(pwd); 21 Properties sshConfig = new Properties(); 22 sshConfig.put("StrictHostKeyChecking", "no"); 23 sshConfig.put("PreferredAuthentications", 24 "password,keyboard-interactive"); 25 sshSession.setConfig(sshConfig); 26 27 28 sshSession.connect(TMOUT);//Timeout can be set 29 //Start mapping ports to local ports here 30 sshSession.setPortForwardingL(Local Port, Destination Node Address, 22); 31 //Once the appeal mapping is complete, you can connect through the local port 32 Session session = jsch.getSession("Target Service User Name", "127.0.0.1",Local Port); 33 Properties remoteCfg = new Properties(); 34 remoteCfg.put("StrictHostKeyChecking", "no"); 35 remoteCfg.put("PreferredAuthentications", 36 "password,keyboard-interactive"); 37 session.setConfig(remoteCfg); 38 session.setPassword("Target Service Password"); 39 session.connect(); 40 //How can I change it later? I use it a lot Online 41 Channel channel = (Channel) session.openChannel("sftp");//Establish sftp Communication Channel 42 channel.connect(); 43 ChannelSftp sftp = (ChannelSftp) channel; 44 45 return sftp; 46 }

Finally, the test successfully accessed the target node's directory via sftp

5 July 2020, 11:04 | Views: 6853

Add new comment

For adding a comment, please log in
or create account

0 comments