前言
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;
shellExecutor.exec(shellParams);
return "0";
}
}
红色标记需要所传参数,路径,时间,等等,根据各自业务而定。
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 String osUsername ="aiadmin";
@Value("${shadow.ksh.server.password}")
private String password;
// private String password = "gAD9$SFT";
private String charset = Charset.defaultCharset().toString();
private Connection conn;
private static final int TIME_OUT = 1000 * 5 * 60;
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();
}
}