1. Java Remote Execution Shell script class
1 Packagecom.test.common.utility;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 Importjava.io.UnsupportedEncodingException;6 ImportJava.nio.charset.Charset;7 8 Importorg.apache.commons.io.IOUtils;9 ImportOrg.apache.commons.logging.Log;Ten Importorg.apache.commons.logging.LogFactory; One A Importch.ethz.ssh2.ChannelCondition; - Importch.ethz.ssh2.Connection; - Importch.ethz.ssh2.Session; the ImportCh.ethz.ssh2.StreamGobbler; - - Public classRmtshellexecutor { - /**Remote machine IP*/ + Private FinalString IP; - /**User name*/ + Private FinalString usr; A /**Password*/ at Private FinalString Psword; - - /** - * Constructor Function - * - * @paramIP in * @paramusr - * @paramPS to */ + Publicrmtshellexecutor (string ip, String usr, string ps) { - This. IP =IP; the This. usr =usr; * This. Psword =PS; $ }Panax Notoginseng - /** the * Execute Script + * A * @paramCmds the * @return + * @throwsException - */ $ Public intEXEC (String cmds)throwsException { $InputStream StdOut =NULL; -InputStream STDERR =NULL; -String outstr = ""; theString Outerr = ""; - intret =-1;Wuyi Try { the if(Login ()) { - //Open A new {@link Session} on this connection WuSession session =conn.opensession (); - //Execute a command on the remote machine. About Session.execcommand (CMDS); $StdOut =NewStreamgobbler (Session.getstdout ()); -OUTSTR =Processstream (StdOut, CharSet); -STDERR =NewStreamgobbler (Session.getstderr ()); -Outerr =Processstream (STDERR, CharSet); A session.waitforcondition (Channelcondition.exit_status, time_out); +System.out.println ("outstr=" +outstr); theSystem.out.println ("outerr=" +outerr); -RET =session.getexitstatus (); $}Else { theLogger.info ("Logon remote machine failed" +IP); the Throw NewAppexception ("Login remote machine failed" + IP);//The implementation of custom exception classes is slightly the } the -}finally { in if(Conn! =NULL) { the conn.close (); the } About ioutils.closequietly (stdOut); the ioutils.closequietly (STDERR); the the } + returnret; - the }Bayi the PrivateString Processstream (InputStream in, String charset)throwsException { the byte[] buf =New byte[1024]; -StringBuilder SB =NewStringBuilder (); - while(In.read (BUF)! =-1) { theSb.append (NewString (BUF, CharSet)); the } the returnsb.tostring (); the - } the}
View Code
2. Call Test
1Rmtshellexecutor exe =NewRmtshellexecutor ("10.190.1.123", "root", "root");2 Try {3 inti = exe.exec ("sh/dcdata/etl/runjobinfo/cscscs.sh");4 System.out.println (i);5}Catch(Exception e) {6 e.printstacktrace ();7Logger.info ("Execute dsjob Error" +e.getmessage ());8}
Update in ...
Java Remote Execution Shell script class