import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* @Description: shell 执行工具类
*/
public class SshCommandUtil {
private static final Logger LOG = LoggerFactory.getLogger(SshCommandUtil.class);
public static Session connect(String ip, String username,String passwd, String port) throws JSchException {
JSch jsch = new JSch();
// 创建JSch对象
Session session = jsch.getSession(username, ip, Integer.valueOf(port));
// 根据用户名、主机ip、端口号获取一个Session对象
session.setPassword(passwd);
// 设置密码
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 为Session对象设置properties
session.setTimeout(150000);
// 设置超时
session.connect();
LOG.info("ip:{}, port: {},连接成功.........................success", ip, port);
return session;
}
public static void execShellCommand(String ip, String username,String passwd, String port, String command) throws JSchException, IOException {
Session session = connect(ip, username, passwd, port);
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
channelExec.setCommand(command);
channelExec.setCommand(command);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
InputStream in = channelExec.getInputStream();
channelExec.connect();
byte[] tmp = new byte[1024];
while (in.available() > 0) {
int i=in.read(tmp,0,1024);
if (i<0) {
break;
}
LOG.info(new String(tmp,0,i));
}
close(session, channelExec);
}
public static void close(Session session, ChannelSftp channelSftp) {
channelSftp.disconnect();
session.disconnect();
LOG.info("session closed success");
}
public static void close(Session session, ChannelExec channelExec) {
session.disconnect();
channelExec.disconnect();
LOG.info("session closed success");
}
public static void upload(String directory, String uploadFile,String fileName, Session session) throws JSchException, FileNotFoundException, SftpException {
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.cd(directory);
File file = new File(uploadFile);
channelSftp.put(new FileInputStream(file), fileName);
LOG.info("文件上传成功: success");
close(session, channelSftp);
file.delete();
}
public static void download(String src, String dst, Session session) throws JSchException, SftpException {
// src linux服务器文件地址,dst 本地存放地址
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.get(src, dst);
close(session, channelSftp);
}
}
Controller层写法:
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static util.AjaxResult.RequestResult.ok;
@Slf4j
@RestController
@RequestMapping("/v1/workFlowInstance")
public class CommonWorkflowInstanceController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(CommonWorkflowInstanceController.class);
@Value("${sttOrderAdd.ip}")
public String ip;
@Value("${sttOrderAdd.user}")
public String user;
@Value("${sttOrderAdd.passwd}")
public String passwd;
@Value("${sttOrderAdd.port}")
public String port;
@Autowired
private CommonWorkflowInstanceService workflowInstanceService;
/**
* @param: [param, request]
* @return: com.alibaba.fastjson.JSONObject
*/
@ApiOperation(value = "数据审核")
@PostMapping(value = "/audit/operation")
public JSONObject settleAdjustOperation(@RequestBody Map<String,Object> param, HttpServletRequest request) {
try {
JSONObject result = workflowInstanceService.settleAdjustOperation(param);
if (null != param.get("bizDataIds") && !CommonMethod.STRING_EMPTY.equals(String.valueOf(param.get("bizDataIds")))) {
try {
String[] bizDataIds = String.valueOf(param.get("bizDataIds")).split(",");
if (null != bizDataIds && bizDataIds.length > 0) {
for (String bizDataId: bizDataIds) {
String command = "sh /app/optps/bin/start.sh " + bizDataId;
log.error("执行的命令:{}", command);
SshCommandUtil.execShellCommand(ip, user, passwd, port, command);
}
}
} catch (Exception e) {
log.error("异常:{}", e.toString());
throw new RuntimeException("异常:{}");
}
}
return result;
} catch (Exception e) {
log.error("审核出现异常:{}", e.toString());
return ok(500).message(e.getMessage()).json();
}
}