SSHFactory { public static void execRemoteBooeEntity( IMessageBuilder mb, SshInfo transitInfo, SshInfo ssh, RemoteBootEntity rbe, int execTimeout) throws JSchException, IOException, SftpException, InterruptedException{ mb.put("=============远程操作:开始============="); PortForwardingHandler portHandler = null; SftpHandler sftpHandler = null; ShellHandler shellHandler = null; int localPort=0; try{ SshInfo newInfo = SerializationUtils.clone(ssh); if(transitInfo!=null){ mb.put("使用SSH安全隧道，代理主机="+transitInfo.getHost()); portHandler = new PortForwardingHandler(transitInfo); localPort = portHandler.startLocalPortForwarding(0, ssh.getHost(), ssh.getPort()); if(localPort <= 0){ throw new SSHException("无法搭建本地到"+ssh.getHost()+":"+ssh.getPort()+"的SSH隧道"); } log.info("open local port forwarding on {}, to {}:{}", localPort, ssh.getHost(), ssh.getPort()); mb.put("开启本地端口%1$d到远程主机%2$s:%3$d的SSH隧道", localPort, ssh.getHost(), ssh.getPort()); newInfo.setHost("localhost").setPort(localPort); }else{ mb.put("不使用SSH安全隧道【不推荐】，由本机直接链接到目标主机"); } shellHandler = new ShellHandler(newInfo); if(rbe.isCheckJava()){ mb.put("检查 java 运行环境（执行 java -version）"); shellHandler.clean().exec("java -version"); String version=shellHandler.getLastResponse(); log.info("执行 java -version 命令，返回值：\n{}", version); mb.put("[返回内容]\n"+version); if(version == null || !version.startsWith("java version")){ mb.put("目标主机没有安装java环境，请先安装最新的java运行环境" + "（执行java -version，能看到java version字样就表示安装成功）"); throw new SSHException(mb.getLast()); } } for(String cmd:rbe.getBeforeCommands()){ mb.put("执行命令："+cmd); shellHandler.clean().exec(cmd); mb.put("[返回内容]\n"+shellHandler.getLastResponse()); log.info("执行{}命令，返回值：\n{}", cmd, shellHandler.getLastResponse()); } sftpHandler = new SftpHandler(shellHandler.getSession()); if(rbe.isClean()){ try{ sftpHandler.rmDir(rbe.getRemotePath()); }catch (Exception e){ mb.put("清空远程目录时出错：" + e.getMessage()); log.error(mb.getLast()); throw e; } } if(rbe.getFileList()!=null && rbe.getFileList().size()>0) { log.info("通过SSH隧道登录到主机{}:{}", ssh.getHost(), ssh.getPort()); if (!sftpHandler.isExist(rbe.getRemotePath())) { mb.put("远程目录%1$s不存在，现在尝试创建...", rbe.getRemotePath()); log.info(mb.getLast()); try { sftpHandler.mkdir(rbe.getRemotePath()); mb.put("目录创建成功"); } catch (Exception e) { mb.put("创建目录时出错：" + e.getMessage()); log.error(mb.getLast()); throw e; } } for (File file : rbe.getFileList()) { String name = file.getName(); String remoteP = rbe.getRemotePath(name); if (rbe.isReplace() || !sftpHandler.isExist(remoteP)) { mb.put("开始上传本地文件%1$s到远程%2$s", file.getAbsoluteFile(), remoteP); log.info(mb.getLast()); sftpHandler.upload(file, remoteP); mb.put("文件上传完成"); log.info(mb.getLast()); } } } String cd = "cd "+rbe.getRemotePath(); shellHandler.clean().exec(cd); mb.put("执行命令：%1$s", cd); log.info(mb.getLast()); mb.put("-----------开始执行afterCommands-------------"); for(String cmd:rbe.getAfterCommands()){ mb.put("执行命令："+cmd); shellHandler.clean().exec(cmd); mb.put("[返回内容]\n"+shellHandler.getResponse()); } mb.put("-----------开始执行启动命令:"+rbe.getStartupCommand()); log.info(mb.getLast()); if(StringUtils.isNotBlank(rbe.getStartupCommand())){ ExecHandler execHandler = new ExecHandler(shellHandler.getSession()); execHandler.exec(rbe.getStartupCommand(), execTimeout); mb.put("执行启动命令：%1$s", rbe.getStartupCommand()); if(execHandler.getResultCode()!=0 || StringUtils.isNotBlank(execHandler.getResultError())){ mb.put("执行启动命令：%1$s 时出错了\n运行时信息：\n%2$s错误信息：\n%3$s", rbe.getStartupCommand(), execHandler.getResult(), execHandler.getResultError()); log.error(mb.getLast()); throw new SSHException("执行启动命令'"+rbe.getStartupCommand()+"'出错!"); }else{ mb.put("\n%1$s", execHandler.getResult()); } } } catch (SSHException e){ throw e; } catch (JSchException e){ throw e; } catch (Exception e){ throw e; }finally { if(localPort>0) portHandler.stopLocalPortForwarding(localPort); if(shellHandler != null){ log.info("----------------关闭ShellHandler----------------"); shellHandler.disconnect(); } if(sftpHandler !=null){ log.info("----------------关闭SftpHandler----------------"); sftpHandler.disconnect(); } if(portHandler != null){ log.info("----------------关闭PortWardingHandler----------------"); portHandler.disconnect(); } mb.put("=============远程操作:结束============="); } }  static int openRemotePortToLocal(
			SshInfo remoteSshInfo,
			int remotePort,
			int localPort); synchronized static int openRemotePortToLocal(
			SshInfo remoteSshInfo,
			int remotePort1,
			int remotePort2,
			int localPort); static void stopRemotePortForwarding(int localPort); static int openLocalPortToRemote(
			SshInfo sshInfo,
			int localPort,
			String remoteHost,
			int remotePort); synchronized static void stopLocalPortForwarding(int port); static boolean isLocalPortUsing(int port); static void disConect(int localPort); @Deprecated static void uploadAndRunJarOnRemoteHost(
			SshInfo transitInfo,
			SshInfo remoteInfo,
			String jarPath,
			String remotePath,
			boolean replaceOnExist,
			String startupCmd,
			int execTimeout); static void execRemoteBooeEntity(
			IMessageBuilder mb,
			SshInfo transitInfo,
			SshInfo ssh,
			RemoteBootEntity rbe,
			int execTimeout); static List<PortLink> getPortLinks(); static synchronized boolean testForSSH(
			SshInfo transitInfo,
			SshInfo remoteInfo);  }
@Test public void testRemoteBoot() throws IOException, InterruptedException, SftpException, JSchException { MessageBuilder mb=new MessageBuilder(); try{ SSHFactory.execRemoteBooeEntity(mb,getSshInfo131(), getSshInfo132(), getRemoteBoot(), 5); }catch (Exception e){ mb.put("执行出错："+e.getMessage()); e.printStackTrace(); } for(String s:mb.getMessageList()) System.out.println(s); }