Java execution shell script shuts down remote database

Source: Internet
Author: User

This example is to start or close the remote MySQL database with Java shell script, demand reason: After the game server, in order to save memory consumption, need to shut down the server unnecessary database (a server host has multiple MySQL database) to improve server performance, But sometimes need to query history game player information, but also need to open the database, in order to save the manpower and time of operation and maintenance personnel, the game backstage provides non-OPS personnel can operate switch database operation.

function Implementation steps:

First: The server background provides parameters, send asynchronous requests, the request method is as follows

<script type= "Text/javascript" >function shutdowndatabase (param,operate) {var arr=param.replace (/\s+/g, ""). Split (""); if (arr.length!=3) {alert ("The database script parameter number is incorrect, please edit it and then do it!") "); return false;} param = param + "" + operate;$.ajax ({url: ' xxxaction!databaseswitch.action ', type: "Post", data:{"param":p aram},datatype : "JSON", async:true,success:function (data) {$ ("#progressImgage"). Hide ();//progress bar hides $ ("#maskOfProgressImage"). Hide () ;//Mask hides alert ("Execution result:" +data.result);},error:function (data) {$ ("#progressImgage"). Hide (); $ ("#maskOfProgressImage")  . hide (); alert ("Execution result:" +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>
Where Param is the shell script parameter, which varies according to the specific business.
Request Wait Prompt code

<div id= "Maskofprogressimage" class= "Mask Hide" ></div><style type= "Text/css" >    . hide{ Display:none}    . progress{z-index:2000}     

Second, the background Java code, send the asynchronous request to the background Java method, the Java method operation executes the shell script, executes the code as follows

/** * Server database switch */public void Databaseswitch () {logger.info ("Server database switch 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\": \ "script parameter cannot be null" + "\"} ");    return;} String shellstr = "sh/data0/mysql_actions.sh" +param;logger.info ("Execute script:" +SHELLSTR); list<string> result = new arraylist<string> (); result = Execshell (SHELLSTR); Out.write ("{\" result\ ": \" "+ Result.tostring () + "\"} "); Logger.info (" Execution result: "+result);} catch (Unsupportedencodingexception E1) {out.write ("{\" result\ ": \" does not support character encoding when manipulating the databaseWrong!  \ "}"); Logger.error ("Execshell method Exception" +e1); E1.printstacktrace ();} catch (Exception e) {out.write ("{\" result\ ": \" Operation database Error!) \ "}"); Logger.error ("Execshell method Exception"); E.printstacktrace ();}      Logger.info ("Server database Switch End");} /** * Run Shell * @param shstr * required to execute shell * @return * @throws IOException */Public STA Tic list<string> Execshell (String shstr) throws Exception {list<string> strlist = new Arraylist<s          Tring> ();          Process process; Process = Runtime.getruntime (). EXEC (new string[]{"/bin/sh", "-C", shstr},null,null);          Execute shell command InputStreamReader ir = new InputStreamReader (Process.getinputstream ());  LineNumberReader input = new LineNumberReader (IR);          Script output String line;  int extvalue = Process.waitfor ();        Execution result Strlist.add ("extvalue=" +extvalue);          while (line = Input.readline ())! = null) {Strlist.add (line); } Process.destroy ();//Kill process RETUrn Strlist;  }

The main way to execute the script is: Execshell (String shstr), where the SHSTR parameter is the shell script to execute, the script in this instance is written directly to the file, so that readability, portability is strong.


Third, close the remote server database

Mainly in the shell script through SSH, connect the remote server, through the script to determine whether the database is open and switch operation, and finally return the results

The key code is:

Ssh= "Ssh-c arcfour128-o [email protected]-O stricthostkeychecking=no-o gssapiauthentication=no-p 22"

$ssh $ "ps-ef |grep mysql |grep \ ' cat/data/${3}/mysql/port\ '" &>/dev/null    if [$?-eq 0];then        echo "Main Library Currently in the running state "    else        $ssh $ sh/data0/${3}/mysql/start-mysql.sh &>/dev/null"        if [$?-eq 0];then            echo "successfully opened the main library"        else            echo "failed to open the main library"        fi    fi

Where the parameter is a remote server IP

Detailed code will not be posted out, the details please direct messages to me. This function is very time-consuming, but when done, others will be very time-saving, the gold content is relatively large.

If the script is not ripe, it needs to be provided by the OPS staff. A person to write needs to know a lot of technology, deep depth.


Issue 1: I encountered a problem during the execution of the script is not executed under the root user, resulting in a failure, the execution of the script must be performed under administrator permissions to succeed.

Issue 2: Background requires the remote server password-free login permissions, through the key settings, SSH also set to "Forwardagent Yes."

Everything is ready backstage can execute, wish readers good luck!






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java execution shell script shuts down remote database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.