標籤:shell java執行shell指令碼 shell關閉資料庫 伺服器
本執行個體為用Java執行shell指令碼啟動或關閉遠程Mysql資料庫,需求原因:遊戲伺服器合服後,為了節省記憶體消耗,需要關閉合服後的伺服器不必要的資料庫(一台伺服器主機存在多個MySql資料庫),以提高伺服器效能,但有時需要查詢曆史遊戲玩家資訊,又需要開啟資料庫,為了節省營運人員的人力和時間,遊戲後台就提供非營運人員都可操作開關資料庫的操作。
功能實現步驟:
第一:伺服器後台提供參數,發送非同步請求,要求方法如下
<script type="text/javascript">function shutdownDatabase(param,operate){var arr=param.replace(/\s+/g," ").split(" ");if(arr.length!=3){alert("資料庫指令碼參數個數不正確,請編輯好再操作!");return false;}param = param + " " + operate;$.ajax({url:'XXXAction!databaseSwitch.action',type:"post",data:{"param":param},dataType:"json",async:true,success:function(data){$("#progressImgage").hide();//進度條隱藏$("#maskOfProgressImage").hide();//蒙版隱藏alert("執行結果:"+data.result);},error:function(data){$("#progressImgage").hide();$("#maskOfProgressImage").hide();alert("執行結果:"+data.result);},beforeSend:function(xhr){$("#progressImgage").show().css({ "position": "fixed", "top": "50%", "left": "50%", "margin-top": function () { return -1 * $("#progressImgage").height() / 2; }, "margin-left": function () { return -1 * $("#progressImgage").width() / 2; } });$("#maskOfProgressImage").show().css("opacity", "0.1");}}); }</script>
其中param為shell指令碼參數,根據具體業務而不同。
請求等待提示代碼
<img id="progressImgage" class="progress hide" alt="資料庫操作中" src="./images/loading.jpg" width="250" height="200"/><div id="maskOfProgressImage" class="mask hide"></div><style type="text/css"> .hide{display:none } .progress{z-index: 2000} .mask{position: fixed;top: 0;right: 0;bottom: 0;left: 0; z-index: 1000; background-color: #000000}</style>
第二,後台java代碼,發送非同步請求到後台java方法,java方法操作執行shell指令碼,執行代碼如下
/** * 伺服器資料庫開關 */public void databaseSwitch() {logger.info("伺服器資料庫開關 start");PrintWriter out = null;try { ActionContext context = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse)context.get(ServletActionContext.HTTP_RESPONSE); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); out= getServletResponse().getWriter(); String param= request.getParameter("param"); if (null == param || "".equals(param)) { out.write("{\"result\":\"指令碼參數不可為空"+"\"}"); return;} String shellStr = "sh /data0/mysql_actions.sh "+param;logger.info("執行指令碼:"+shellStr);List<String> result = new ArrayList<String>();result = execShell(shellStr);out.write("{\"result\":\""+result.toString()+"\"}");logger.info("執行結果:"+result);} catch (UnsupportedEncodingException e1) {out.write("{\"result\":\"操作資料庫時不支援字元編碼出錯!\"}");logger.error("execShell方法異常"+e1);e1.printStackTrace();} catch (Exception e) {out.write("{\"result\":\"操作資料庫出錯!\"}");logger.error("execShell方法異常");e.printStackTrace();}logger.info("伺服器資料庫開關 end");} /** * 運行shell * @param shStr * 需要執行的shell * @return * @throws IOException */ public static List<String> execShell(String shStr) throws Exception { List<String> strList = new ArrayList<String>(); Process process; process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null); ////執行shell命令 InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); //指令碼輸出 String line; int extValue = process.waitFor(); //執行結果 strList.add("extValue="+extValue); while ((line = input.readLine()) != null){ strList.add(line); } process.destroy();//殺掉進程 return strList; }
執行指令碼的主要方法為:execShell(String shStr),其中shStr參數為要執行的shell指令碼,本執行個體的指令碼寫成檔案直接調用,這樣可讀性,可移植性強。
第三,關閉遠程伺服器資料庫
主要是在shell指令碼中通過ssh,串連遠程伺服器,通過指令碼判斷資料庫是否開啟並執行開關操作,最後返回結果
關鍵代碼為:
ssh="ssh -c arcfour128 -o [email protected] -o StrictHostKeyChecking=no -o GSSAPIAuthentication=no -p 22"
$ssh $1 "ps -ef |grep mysql |grep \`cat /data/${3}/mysql/port\`" &> /dev/null if [ $? -eq 0 ];then echo "主庫目前已經處於運行狀態" else $ssh $1 "sh /data0/${3}/mysql/start-mysql.sh &> /dev/null" if [ $? -eq 0 ];then echo "成功開啟主庫" else echo "開啟主庫失敗" fi fi
其中$1參數為遠程伺服器ip
詳細代碼就不貼出來了,詳解請私信我。這個功能做出來是非常耗時的,但做出來後,別人就很省時了,含金量比較大。
如果指令碼不熟,需要營運人員提供。一個人寫需要懂的技術很多,深度很深。
問題1:我執行指令碼期間遇到一個問題就是沒有在root使用者下執行,導致失敗,執行指令碼需在管理員權限下執行才能成功。
問題2:後台需要遠程伺服器的無密碼登入許可權,通過key設定,ssh還要設定為“ForwardAgent yes”。
一切就緒後台即可執行,祝讀者好運!
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java執行shell指令碼關閉遠端資料庫