java调用shell脚本并传递参数
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                java调用shell脚本并传递参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                最近業務上需要java調用執行shell腳本進行一些業務處理,寫了個demo,記錄下。
主要代碼
?? ?@RequestMapping("/copy/database")@ResponseBodypublic String copyDatabase(HttpServletRequest request,String dbCode,String targetPath){JSONObject result = new JSONObject();String osname = System.getProperty("os.name");if ((osname != null) && (osname.toLowerCase().startsWith("win"))){LOG.info("當前操作系統是:"+osname);result.put("code", "0");result.put("msg", "當前服務器操作系統不是linux");return result.toJSONString();}LOG.info("接收到參數:dbCode=" + dbCode + " targetDbNfsPath=" + targetPath);if(StringUtil.isBlank(dbCode) || StringUtil.isBlank(targetPath)){result.put("code", "0");result.put("msg", "dbCode/targetPath不能為空");return result.toJSONString();}String dir = DbDirConstant.findDir(dbCode);if(StringUtil.isBlank(dir)){result.put("code", "0");result.put("msg", "根據dbCode找不到對應的數據庫目錄");return result.toJSONString();}//腳本路徑String shellPath = request.getServletContext().getRealPath("/")+"WEB-INF/classes";String cmd = shellPath + "/copyDB.sh "+ dir + " " + targetPath;ProcessBuilder builder = new ProcessBuilder("/bin/sh","-c",cmd);builder.directory(new File(shellPath));int runningStatus = 0;String s = null;StringBuffer sb = new StringBuffer();try {Process p = builder.start();BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));while ((s = stdInput.readLine()) != null) {LOG.info("shell log info ...." + s);sb.append(s);}while ((s = stdError.readLine()) != null) {LOG.error("shell log error...." + s);sb.append(s);}try {runningStatus = p.waitFor();} catch (InterruptedException e) {runningStatus = 1;LOG.error("等待shell腳本執行狀態時,報錯...",e);sb.append(e.getMessage());}closeStream(stdInput);closeStream(stdError);} catch (Exception e) {LOG.error("執行shell腳本出錯...",e);sb.append(e.getMessage());runningStatus =1;}LOG.info("runningStatus = " + runningStatus);if(runningStatus == 0){//成功result.put("code", "1");result.put("msg", "成功");return result.toJSONString();}else{result.put("code", "0");result.put("msg", "調用shell腳本復制數據庫時失敗..." + sb.toString());return result.toJSONString();}}private void closeStream(BufferedReader reader){try {if(reader != null){reader.close();}} catch (Exception e) {reader = null;}}其中shell
#!/bin/bashecho 'copy db start....'dbBack=/databaseBack nfsDir=/targetDbNfs state=0cd /if [ ! -d "$nfsDir" ];thenmkdir -p $nfsDir fi## mount target db echo 'ready mount target db...' mount -t nfs $2 $nfsDirif [ $? -eq 0 ]thenecho 'mount target db success...'elseecho 'mount target db fail...'exit 1 fiecho 'ready copy....' ## cp will tip y/n, so use \cp? \cp -rf $dbBack/$1/* $nfsDir/if [ $? -eq 0 ]thenecho 'copy success...'elseecho 'copy fail...'$state=1 fiumount $nfsDirexit $state注意事項:
 1.shell腳本必須有執行權限,比如部署后chmod -R 777 /webapps
2.shell文件,必須是UNIX格式,ANSI編碼格式,否則容易出問題(可以用notepad++,編輯->文檔格式轉換,格式->轉為ANSI格式
 ?
總結
以上是生活随笔為你收集整理的java调用shell脚本并传递参数的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: php跳一跳小游戏,原生JS实现的跳一跳
 - 下一篇: Struts2源码阅读(三)_Dispa