Use the JSCH framework to access other nodes through the jump machine.
Previously, I developed a code for Remotely accessing ssh for operations. Recently, a jump server is required to access the target service. After searching for a long time on the Internet and failing to find a good example, I read JSCH's API. But you can see it in the dark. Lenovo, does port forwarding map the target node ip: port to localhost: port, and then send a message through localhost: port to reach the target node?
With this inference, we transformed the previous code.
The original code uses jsch to connect to the target node server. I will not talk about it here. I am using Baidu and there are a lot of Internet resources.
The following is the modified Code:
1/** 2 * Get connection 3 * @ param ip jump host 4 * @ param userName jump host user name 5 * @ param pwd jump host password 6 * @ param port jump host 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 JSchException11 {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); // you can set the timeout value 29 // The port is mapped to the local part 30 sshSession. setPortForwardingL (local port, target Node Address, 22); 31 // after the appeal ing is completed, the 32 Session session = jsch can be connected through the local port. getSession ("target service username", "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 to change it on your own in the future. There are many 41 Channel channel = (Channel) sessions on the Internet. openChannel ("sftp"); // creates an sftp communication channel 42 channel. connect (); 43 ChannelSftp sftp = (ChannelSftp) channel; 44 45 return sftp; 46}
View Code
Finally, the target node directory is accessed through sftp.