標籤:
1、java遠程執行shell指令碼類
1 package com.test.common.utility; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.UnsupportedEncodingException; 6 import java.nio.charset.Charset; 7 8 import org.apache.commons.io.IOUtils; 9 import org.apache.commons.logging.Log;10 import org.apache.commons.logging.LogFactory;11 12 import ch.ethz.ssh2.ChannelCondition;13 import ch.ethz.ssh2.Connection;14 import ch.ethz.ssh2.Session;15 import ch.ethz.ssh2.StreamGobbler;16 17 public class RmtShellExecutor {18 /** 遠程機器IP */19 private final String ip;20 /** 使用者名稱 */21 private final String usr;22 /** 密碼 */23 private final String psword;24 25 /**26 * 建構函式27 * 28 * @param ip29 * @param usr30 * @param ps31 */32 public RmtShellExecutor(String ip, String usr, String ps) {33 this.ip = ip;34 this.usr = usr;35 this.psword = ps;36 }37 38 /**39 * 執行指令碼40 * 41 * @param cmds42 * @return43 * @throws Exception44 */45 public int exec(String cmds) throws Exception {46 InputStream stdOut = null;47 InputStream stdErr = null;48 String outStr = "";49 String outErr = "";50 int ret = -1;51 try {52 if (login()) {53 // Open a new {@link Session} on this connection54 Session session = conn.openSession();55 // Execute a command on the remote machine.56 session.execCommand(cmds);57 stdOut = new StreamGobbler(session.getStdout());58 outStr = processStream(stdOut, charset);59 stdErr = new StreamGobbler(session.getStderr());60 outErr = processStream(stdErr, charset);61 session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);62 System.out.println("outStr=" + outStr);63 System.out.println("outErr=" + outErr);64 ret = session.getExitStatus();65 } else {66 logger.info("登入遠程機器失敗" + ip);67 throw new AppException("登入遠程機器失敗" + ip); // 自訂異常類 實現略68 }69 70 } finally {71 if (conn != null) {72 conn.close();73 }74 IOUtils.closeQuietly(stdOut);75 IOUtils.closeQuietly(stdErr);76 77 }78 return ret;79 80 }81 82 private String processStream(InputStream in, String charset) throws Exception {83 byte[] buf = new byte[1024];84 StringBuilder sb = new StringBuilder();85 while (in.read(buf) != -1) {86 sb.append(new String(buf, charset));87 }88 return sb.toString();89 90 }91 }
View Code
2、調用測試
1 RmtShellExecutor exe = new RmtShellExecutor("10.190.1.123", "root", "root");2 try {3 int i = exe.exec("sh /dcdata/etl/runjobinfo/cscscs.sh");4 System.out.println(i);5 } catch (Exception e) {6 e.printStackTrace();7 logger.info("執行dsjob錯誤" + e.getMessage());8 }
更新中。。。
JAVA遠程執行Shell指令碼類