远程调用cmd更新本地jar
最近遇到一个项目需求需要实现远程更新,但是本地项目无法更新自己,这让博主很是头疼,既然自己无法更新自己的话,那就自建新的项目,通过本地项目来调用新项目接口来更新本地项目。
代码如下:
/** * 重启完成更新 */ public boolean restart() { log.info("restart"); String command = "cmd /c start C:\\rct\\winsw\\rct\\update.bat"; //测试 String distName = "dist"; String jarName = "rct-demo-1.0.jar"; String bat; if (type.equals("dist")) { log.info("dist"); bat = "@echo off\n" + "%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c %~s0 ::\",\"\",\"runas\",1)(window.close)&&exit\n" + "cd /d \"%~dp0\"\n" + "net stop \"" + webService + "\"" + "\n" + "rmdir /S /Q " + targetFile + "\\" + "dist" + "\n" + "xcopy /Y /E /i " + sourceFile + "\\" + distName + " " + targetFile + "\\" + distName + "\n" + "net start \"" + webService + "\""; } else if (type.equals("jar")) { log.info("jar"); bat = "@echo off\n" + "%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c %~s0 ::\",\"\",\"runas\",1)(window.close)&&exit\n" + "cd /d \"%~dp0\"\n" + "net stop \"" + jarService + "\"" + "\n" + "xcopy /Y /E /i " + sourceFile + "\\" + jarName + " " + targetFile + "\\" + jarName + "\n" + "net start \"" + jarService + "\""; } else { log.info("all"); bat = "@echo off\n" + "%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c %~s0 ::\",\"\",\"runas\",1)(window.close)&&exit\n" + "cd /d \"%~dp0\"\n" + "net stop \"" + jarService + "\"" + "\n" + "net stop \"" + webService + "\"" + "\n" + "rmdir /S /Q " + targetFile + "\\" + "dist" + "\n" + "xcopy /Y /E /i " + sourceFile + "\\" + jarName + " " + targetFile + "\\" + jarName + "\n" + "xcopy /Y /E /i " + sourceFile + "\\" + distName + " " + targetFile + "\\" + distName + "\n" + "net start \"" + jarService + "\"" + "\n" + "net start \"" + webService + "\""; } creatBat(bat); log.info("cmd exec"); try { if (HttpUtil.isConnect(checkUrl)) { updated = true; try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } HttpUtil.HttpClientPost(cmdUrl, command); } else { errored = true; return false; } } catch (Exception e) { log.error("http请求异常"); e.printStackTrace(); errored = true; return false; } log.info("cmd success"); return true; } public void creatBat(String bat) { FileWriter fw = null; try { fw = new FileWriter("C:\\rct\\winsw\\rct\\update.bat"); fw.write(bat); } catch (IOException e) { e.printStackTrace(); } finally { if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }