Java SSH remote execution shell command, Shell script implementation (ganymed SSH)

Source: Internet
Author: User

Jar Package:

http://www.ganymed.ethz.ch/ssh2/

The advantage of this source is not dependent on a lot of other packages, copy come clean. Specific code implementation can be seen below, or refer to the official documentation, in the download of the compressed package Ganymed-ssh2-build210\examples directory has an example.

 Packagecom.system.action; ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;Importorg.springframework.web.bind.annotation.RequestMapping;ImportCom.system.service.MonitorService;Importch.ethz.ssh2.Connection;Importch.ethz.ssh2.Session;ImportCh.ethz.ssh2.StreamGobbler;ImportUtil.dataSource.SwitchDataSourceUtil;Importutil.page.BaseAction; /*** Server monitoring *@authorWangxiangyu **/@Controller @requestmapping ("/monitor") @SuppressWarnings ("All") Public classMonitorcontrollerextendsbaseaction {Private Staticlist<string> commands =NULL;Private Static FinalString JNDI = "PN";//Love OPS administrator rights data source@AutowiredMonitorService Monitorservice;/*** Go to the monitoring page to get the server configuration (IP, login, password) *@paramRequest *@parammodel *@return */@RequestMapping (Value= "/index.do") PublicString Index (HttpServletRequest request, model model) {string HostName= Request.getparameter ("HostName"); List<map<string, string>> serverconfiglist =Monitorservice.getserverconfig (hostName); Model.addattribute ("Serverconfiglist", serverconfiglist);return"System/monitor/monitor";} /*** Initialize command set*/Private voidinitcommands () {commands=NewArraylist<string>(); Commands.add ("Top"); Commands.add ("Free"); Commands.add ("Df-hl"); Commands.add ("Ps-ef|grep Tomcat"); Commands.add ("PS aux|head-1;ps aux|grep-v pid|sort-rn-k +4|head");} /*** Get server running status *@paramRequest *@paramResponse *@throwsException*/@RequestMapping ("/findstatus.do") Public voidFindstatus (HttpServletRequest request, httpservletresponse response)throwsException {//Get Server configuration informationString hostName = Request.getparameter ("HostName"); List<map<string, string>> serverconfiglist =Monitorservice.getserverconfig (hostName); String UserName= Serverconfiglist.get (0). Get ("user_name"). toString (); String Password= Serverconfiglist.get (0). Get ("PASSWORD"). toString ();//pre-defined result setmap<string, object> result =NewHashmap<string, object>();//predefined command result setlist<map<string, string>> commandresults =NewArraylist<map<string, string>>();Try {//connecting to a serverConnection conn =NewConnection (hostName); Conn.connect ();BooleanIsAuthenticated =Conn.authenticatewithpassword (userName, password);if(IsAuthenticated = =false) {Throw NewIOException ("Authentication failed.");}//Initialize command parametersinitcommands (); for(String command:commands) {Session sess=conn.opensession (); sess.execcommand (command); InputStream stdout=NewStreamgobbler (Sess.getstdout ()); BufferedReader BR=NewBufferedReader (NewInputStreamReader (stdout)); StringBuffer Details=NewStringBuffer (""); while(true) {String line=br.readline ();if(line = =NULL) { Break;} Details.append (line). Append ("<br/>"); SYSTEM.OUT.PRINTLN (details);}//Package Resultsmap<string, string> Commandresult =NewHashmap<string, string>(); Commandresult.put ("HostName", HostName); Commandresult.put ("Command", command); Commandresult.put ("ExitCode",NULL==sess.getexitstatus ()? " No: Sess.getexitstatus (). toString ()); Commandresult.put ("Details", (NULL==details)? " No return result ":d etails.tostring ()); Commandresults.add (Commandresult);//Close the streambr.close (); Sess.close ();} Conn.close (); Result.put ("Rows", commandresults);}Catch(IOException e) {e.printstacktrace (system.err);}  Write (response, result);} /*** View database table space Status *@paramRequest *@paramResponse *@throwsIOException*/@RequestMapping ("/getdbstatus.do") Public voidGetDBStatus (HttpServletRequest request, httpservletresponse response)throwsIOException {List<map<string, string>> Dbresult =NewArraylist<map<string,string>>();Try {//Toggle Data SourceSwitchdatasourceutil.setcurrentdatasource (JNDI);d bresult=Monitorservice.getdbstatus (); Switchdatasourceutil.cleardatasource ();}Catch(Exception e) {e.printstacktrace ();}finally{Switchdatasourceutil.cleardatasource ();} Map<string, object> result =NewHashmap<string, object>(); Result.put ("Rows", Dbresult); write (response, result);}}

Java SSH remote execution shell command, Shell script implementation (ganymed SSH)

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.