I have previously created a set of codes for remote access to ssh. Recently, there is a requirement and I need to go through a jump machine to access the target service. After searching online for a long time, I couldn't find a better example, so I looked through the JSCH API by myself. But I saw it in a fog. After all, I think about it, is the principle of port forwarding to 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, I modified the previous code.
I won’t say much about the original code that connects to the target node server through jsch. I’ll use Baidu to do it, and there are many online.
The following is the modified code:
/** * Get the connection* @param ip Jump host * @param userName Jump username * @param pwd Jump password * @param port Jump port * @return ChannelSftp Return value * @throws JSchException Connection exception*/ public static ChannelSftp connect(String ip, String userName, String pwd, int port) throws JSchException { if (port <= 0) { port = PORT; } Session sshSession = null; JSch jsch = new JSch(); sshSession = jsch.getSession(userName, ip, port); sshSession.setPassword(pwd); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshConfig.put("PreferredAuthentications", "password,keyboard-interactive"); sshSession.setConfig(sshConfig); sshSession.connect(TMOUT);//The timeout can be set//The part of the port mapped to the local sshSession.setPortForwardingL(local port, target node address, 22); //After completing the appeal mapping, you can connect to the Session session = jsch.getSession("target service username", "127.0.0.1", local port); Properties remoteCfg = new Properties(); remoteCfg.put("StrictHostKeyChecking", "no"); remoteCfg.put("PreferredAuthentications", "password,keyboard-interactive"); session.setConfig(remoteCfg); session.setPassword("target service password"); session.connect(); //How to change it yourself in the future? There are many channels used online. Channel = (Channel) session.openChannel("sftp");//Create sftp communication channel channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; return sftp; }Finally, the test was used to access the target node's directory through sftp, and it was successful.
The above method of using the JSCH framework to access other nodes through a jump machine is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.