"Original" Java program calls remote shell script

Source: Internet
Author: User
Tags call shell

The purpose of this program is to execute shell scripts on the remote machine.

"Environment Parameters"
Remote machine ip:192.168.234.123
User name: Root
Password: root
Path to shell script:/home/ifilegentool/bakprovisionandoccurentrance.sh

"Concrete Steps"
1. On the remote machine, prepare the shell script.
[[email protected] ifilegentool]# vim./load_data.sh

1#!/bin/SH2source/etc/ Profile3dbname=$14tablename=$25 Echo[`Date+'%y-%m-%d%h:%m:%s'`]'start loading Data ...'6mysql-uroot-p123456-p3306 ${dbname}-E"LOAD DATA LOCAL INFILE '/home/ifilegento ol_zhangjian/bak_data/t_acc_subject_provision_data_bak.txt ' into TABLE $     {TableName} Fields TERMINATED by '; '"7 Echo[`Date+'%y-%m-%d%h:%m:%s'`]'End Loading Data ...'8 Exit9Eof

2. Import the jar packages that need to be relied upon.
Java Remote Call Shell script This program requires Ganymed-ssh2-build210.jar package.
: http://www.ganymed.ethz.ch/ssh2/
For debugging convenience, the code under the \GANYMED-SSH2-BUILD210\SRC can be copied directly into our project,
The advantage of this source is not dependent on a lot of other packages, copy come clean.

1 <Dependency>2     <groupId>Org.jvnet.hudson</groupId>3     <Artifactid>Ganymed-ssh2</Artifactid>4     <version>Build210-hudson-1</version>5 </Dependency>


3, write Remoteshellexecutor tool class.

1 Importjava.io.IOException;2 ImportJava.io.InputStream;3 Importjava.io.UnsupportedEncodingException;4 ImportJava.nio.charset.Charset;5 6 Importorg.apache.commons.io.IOUtils;7 8 Importch.ethz.ssh2.ChannelCondition;9 Importch.ethz.ssh2.Connection;Ten Importch.ethz.ssh2.Session; One ImportCh.ethz.ssh2.StreamGobbler; A  -  Public classRemoteshellexecutor { -       the      PrivateConnection Conn; -      /**Remote machine IP*/ -      PrivateString IP; -      /**User name*/ +      PrivateString Osusername; -      /**Password*/ +      PrivateString password; A      PrivateString charset =Charset.defaultcharset (). toString (); at  -      Private Static Final inttime_out = 1000 * 5 * 60; -  -      /** - * Constructor Function -       * @paramIP in       * @paramusr -       * @paramPasword to       */ +       Publicremoteshellexecutor (string ip, String usr, string pasword) { -            This. IP =IP; the           This. Osusername =usr; *           This. Password =pasword; $      }Panax Notoginseng  -  the      /** + * Login A      * @return the      * @throwsIOException +      */ -      Private BooleanLogin ()throwsIOException { $conn =NewConnection (IP); $ Conn.connect (); -          returnConn.authenticatewithpassword (osusername, password); -      } the  -      /**Wuyi * Execute Script the      *  -      * @paramCmds Wu      * @return -      * @throwsException About      */ $       Public intEXEC (String cmds)throwsException { -InputStream StdOut =NULL; -InputStream STDERR =NULL; -String outstr = ""; AString Outerr = ""; +          intret =-1; the          Try { -          if(Login ()) { $              //Open A new {@link Session} on this connection theSession session =conn.opensession (); the              //Execute a command on the remote machine. the Session.execcommand (CMDS); the               -StdOut =NewStreamgobbler (Session.getstdout ()); inOUTSTR =Processstream (StdOut, CharSet); the               theSTDERR =NewStreamgobbler (Session.getstderr ()); AboutOuterr =Processstream (STDERR, CharSet); the               the session.waitforcondition (Channelcondition.exit_status, time_out); the               +System.out.println ("outstr=" +outstr); -System.out.println ("outerr=" +outerr); the              BayiRET =session.getexitstatus (); the}Else { the              Throw NewException ("Login remote machine failed" + IP);//The implementation of custom exception classes is slightly -          } -}finally { the              if(Conn! =NULL) { the conn.close (); the              } the ioutils.closequietly (stdOut); - ioutils.closequietly (STDERR); the          } the          returnret; the      }94  the      /** the      * @paraminch the      * @paramCharSet98      * @return About      * @throwsIOException -      * @throwsunsupportedencodingexception101      */102      PrivateString Processstream (InputStream in, String charset)throwsException {103          byte[] buf =New byte[1024];104StringBuilder SB =NewStringBuilder (); the           while(In.read (BUF)! =-1) {106Sb.append (NewString (BUF, CharSet));107          }108          returnsb.tostring ();109      } the 111      Public Static voidMain (String args[])throwsException { theRemoteshellexecutor executor =NewRemoteshellexecutor ("192.168.234.123", "root", "Beebank");113         //execute the mytest.sh parameter for Java Know dummy theSystem.out.println (Executor.exec ("/home/ifilegentool/load_data.sh t_users myDataBase01")); the     } the}

4. Operation result
Outstr=java Know 3
Outerr=
0//Getexitstatus return value of method

Note: In general, the shell script executes normally, and the Getexitstatus method returns 0.
This method obtains exit Code/status through a remote command. However, this value is not returned at each server design time, and null is returned if none.
When calling Getexitstatus, the Waitforcondition method is called first, and the specific meaning of each condition can be seen through the definition of the Channelcondition.java interface. See the following code:
Source code for Channelcondition.java

Reference connection: http://yu.you163.blog.163.com/blog/static/339877742012117101039968/

"Original" Java program calls remote shell script

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.