Java遠端呼叫shell指令碼(專案實戰)
前言
Java遠端呼叫shell指令碼,需要用到SSH建立連結(類似於xshell連線linux),然後再根據合法的引數進行shell指令碼呼叫
1 首先,從業務層開始,我這裡實現重傳指令碼的業務,程式碼如下.
//重傳 public String reUpload(Upload upload) throws Exception{ Map<String,Object> param = new HashMap<String,Object>(); param.put("fileId", upload.getFileId()); String procedureCode = daliyRunLogMapper.getProcedureCode(param); if(procedureCode == null || "".equals(procedureCode)){ return "1"; }else{ String time = upload.getDateTime(); String fileId = upload.getFileId(); String path = " /asiainfo/aiadmin/jtcollection/onlineCompaniesNew/shell/day/upload_sd_main.sh"; String shellParams = path+" "+time+" "+fileId+" "+procedureCode;
紅色標記需要所傳引數,路徑,時間,等等,根據各自業務而定。
2 接著,新建一個公共CommonShellExecutor.class ,程式碼如下
import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;
import ch.ethz.ssh2.ChannelCondition; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler;
@Component public class CommonShellExecutor { @Value("${shadow.ksh.server.ip}") private String ip; // private String ip ="10.109.1.142"; @Value("${shadow.ksh.server.username}") private String osUsername
private boolean login() throws IOException { conn = new Connection(ip); conn.connect();//建立連線 return conn.authenticateWithPassword(osUsername, password);//根據使用者名稱密碼,進行校驗 }
public int exec(String cmds) throws Exception { InputStream stdOut = null; InputStream stdErr = null; String outStr = ""; String outErr = ""; int ret = -1; try { if (login()) { // Open a new {@link Session} on this connection Session session = conn.openSession(); // Execute a command on the remote machine. session.execCommand(cmds); stdOut = new StreamGobbler(session.getStdout()); outStr = processStream(stdOut, charset); stdErr = new StreamGobbler(session.getStderr()); outErr = processStream(stdErr, charset); session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); System.out.println("outStr=" + outStr); System.out.println("outErr=" + outErr); ret = session.getExitStatus(); } else { throw new Exception("登入遠端機器失敗" + ip); // 自定義異常類 實現略 } } finally { if (conn != null) { conn.close(); } IOUtils.closeQuietly(stdOut); IOUtils.closeQuietly(stdErr); } return ret; }
private String processStream(InputStream in, String charset) throws Exception { byte[] buf = new byte[1024]; StringBuilder sb = new StringBuilder(); while (in.read(buf) != -1) { sb.append(new String(buf, charset)); } return sb.toString(); } }