java远程调用shell脚本

使用的时候直接复制相应的类即可
导入依赖

 <dependency>
     <groupId>org.jvnet.hudson</groupId>
     <artifactId>ganymed-ssh2</artifactId>
     <version>build210-hudson-1</version>
 </dependency>
package com.tansun.datagovern.east.util;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.*;
import java.nio.charset.Charset;

public class RemoteShellExecutor {

    private Connection conn;
    private String ip;
    private String username;
    private String password;
    private static final int TIME_OUT = 1000 * 60;// 表示不超时
    private String charset = Charset.defaultCharset().toString();

    public RemoteShellExecutor(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }

    private boolean login() throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(username, password);
    }

    public String exec(String shell) throws Exception {
        Session session = null;
        InputStream stdOut = null;
        InputStream stdErr = null;
        PrintWriter pw;
        String outStr, outErr;
        try{
            if (login()) {
                //跨服务器远程调用shell脚本需要配置
                session = conn.openSession();
                session.requestPTY("bash");
                session.startShell();
                pw = new PrintWriter(session.getStdin());
                pw.println(shell);
                pw.println("exit");
                pw.close();
                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);
            } else {
                throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
            }
        }finally {
            if (stdOut != null) {
                stdOut.close();
            }
            if (stdErr != null) {
                stdErr.close();
            }
            if (session != null) {
                session.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
        if (outStr.contains("ERROR")){
            return "存储过程运行失败"+outStr;
        }else if (outErr.length()>0){
            return "shell调用失败";
        }else {
            return "";
        }

    }

    private String processStream(InputStream in, String charset) throws Exception {
        StringBuilder sb = new StringBuilder();
        BufferedReader brs = new BufferedReader(new InputStreamReader(in, charset));
        for (String line = brs.readLine(); line != null; line = brs.readLine()) {
            sb.append(line).append(System.getProperty("line.separator"));
        }
        return sb.toString();
    }



}

package com.tansun.datagovern.east.controller;


import com.tansun.common.core.annotation.OperLog;
import com.tansun.common.core.utils.DateUtil;
import com.tansun.common.core.web.JsonResult;
import com.tansun.datagovern.east.mapper.RemoteShellMapper;
import com.tansun.datagovern.east.util.RemoteShellExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/east")
public class RemoteShellController {

    @Value("${shellIp}")
    private String shellIp;
    @Value("${shellUserName}")
    private String shellUserName;
    @Value("${shellPassWord}")
    private String shellPassWord;
    @Value("${oracleUserName}")
    private String userName;
    @Value("${oraclePassWord}")
    private String userPwd;

    @Autowired
    private RemoteShellMapper remoteShellMapper;


    @GetMapping(value = "callShell")
    public JsonResult callShell(Date dataDt){
        int dd = Integer.parseInt(DateUtil.dateToString(new Date(), "yyyyMMdd").substring(6));

        if (dd>15){
            return JsonResult.error("每月15号后不可抽数操作");
        }
        if (dataDt == null||"".equals(dataDt)){
            return JsonResult.error("请选择日期");
        }
        //登录远程服务器
        RemoteShellExecutor executor = new RemoteShellExecutor(shellIp, shellUserName, shellPassWord);
        String date = DateUtil.formatDate(dataDt,"yyyyMMdd");
        //shell脚本中要调用的存储过程名称
        String procName = "PRO_EAST_MAKEUP_INIT";
        //拼接shell调用命令
        String cmds = "sh /home/oracle/choushu.sh" +" "+ date +" "+procName + " " +userName+ " " +userPwd;
        String exec = "";
        try {
            exec = executor.exec(cmds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("".equals(exec)){
            return JsonResult.ok("调用成功");
        }else {
            return JsonResult.error(exec);
        }

    }

    @GetMapping(value = "dataCheck")
    public JsonResult dataCheck() {
        Date date = new Date();
        String yyyyMMdd = DateUtil.formatDate(date, "yyyyMMdd");
        Map<String, Object> map = new HashMap<String, Object>();
        //需要传入存储过程返回参数
        map.put("Vdate",yyyyMMdd);
        map.put("Vreturn","V_RETURN");
        map.put("Vmsg","V_MSG");
        remoteShellMapper.getCheckProcedure(map);
        if ((Integer) map.get("Vreturn") ==0){
            return  JsonResult.ok("检核成功");
        }else {
            return  JsonResult.error("检核失败"+map.get("Vmsg"));
        }

    }

    @GetMapping(value = "dataRemoval")
    public JsonResult dataRemoval() {
        Date date = new Date();
        String yyyyMMdd = DateUtil.formatDate(date, "yyyyMMdd");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("Vreturn","V_RETURN");
        map.put("Vmsg","V_MSG");
        map.put("Vdate",yyyyMMdd);
        remoteShellMapper.getRemovalProcedure(map);
        if ((Integer) map.get("Vreturn") ==0){
            return  JsonResult.ok("执行成功");
        }else {
            return  JsonResult.error("执行失败"+map.get("Vmsg"));
        }
    }


}

absHolderListSh:
  shpath: /home/ccbt/xxpl/sqlldr/xxpl_sqlldr_main.sh
  tableName: REP_ID_ABS_HOLDER_LIST_SS
  orcaleConn: xxpltest/xxpltest@172.16.1.188:1521/datahouse
  sftpUser: bigdata
  sftpPass: BigData12#$
  sftpIp: 172.16.1.232
跑存储脚本:/home/ccbt/call_pro.sh
参数1:数据库名
参数2:存储名
参数3:数据日期

推数脚本:/home/ccbt/sftp_push_data_custview_file.sh
参数1:warehouse
参数2:数据文件存放目录名
参数3:数据库名
参数4:表名
参数5:表类型代码
参数6:数据日期
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值