Java接口执行Shell 工具类+Controller



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();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值