【JSch】JSch通过堡垒机连接内网
pom
<!-- jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.16</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency>
代码
Session session = JschUtil.getSession("堡垒机IP", 堡垒机开放端口, "堡垒机用户名", "堡垒机密码"); JschUtil.bindPort(session, "内网iP", 内网端口, 内网端口映射到的堡垒机端口(一般为堡垒机开放端口) ); Properties sessionConfig = new Properties(); // 去掉首次连接确认 sessionConfig.put("StrictHostKeyChecking", "no"); session.setConfig(sessionConfig); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setCommand("pwd"); channelExec.connect(); InputStream inputStream = channelExec.getInputStream(); String result = new String(ByteStreams.toByteArray(inputStream)); System.out.println(result);