java程序登录服务器执行命令

<dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
</dependency>
import com.google.common.base.Strings;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dongl
 * @date 2020/9/4 17:33
 */

public class RmiExecutor {
  private static Logger logger = LoggerFactory.getLogger(RmiExecutor.class) ;
  public static Map<String,Object> exec(Map<String, Object> executeInfo){
    Map<String,Object> execResult=new HashMap<>();
    InputStream stdOut = null;
    InputStream stdErr = null;
    execResult.put("resultCode","0");
    execResult.put("resultMsg","操作成功");
    try {
      String command=executeInfo.get("command").toString();
      Session session = getSession(executeInfo);
      ChannelExec exec = (ChannelExec) session.openChannel("exec");
      exec.setCommand(command);
      int exitStatus = exec.getExitStatus(); //未执行 -1
      logger.error("exitStatus的值:{} ", exitStatus);
      stdOut = exec.getInputStream();
      stdErr = exec.getErrStream();
      exec.connect(30000);
      String output = processOutput(stdOut, executeInfo);
      String errorOut = "";
      if (Strings.isNullOrEmpty(output)) {
        errorOut = processOutput(stdErr, executeInfo);
      }
      execResult.put("data",output + "\n" + errorOut);
      //logger.error("exitStatus的值:{} ", exec.getExitStatus()); 已执行 0
      exec.disconnect();
      session.disconnect();
    } catch (Exception e) {
      execResult.put("resultMsg","操作失败");
      execResult.put("data",e.getMessage());
      execResult.put("resultCode","-1");
      logger.error("command execute fail ", e);
    }finally{
      try {
        if (stdOut != null) {
          stdOut.close();
        }
        if (stdErr != null) {
          stdErr.close();
        }
        execResult.put("exeTime",DateUtil.dateTimeToString(new Date()));
      } catch (Exception ignore) {
      }
    }
    return execResult;
  }
  private static String processOutput(InputStream stdOut, Map<String, Object> executeInfo) throws IOException {
    String result="";
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdOut));
    String buf = null;
    while ((buf = reader.readLine()) != null) {
      result+= new String(buf.getBytes("gbk"),"UTF-8")+"    <br>\r\n";
    }
    logger.info("stdOut的值:{} \n executeInfo的值:{} ",stdOut,executeInfo);
    return result;
  }
  private static Session getSession(Map<String, Object> executeInfo) throws JSchException {
    JSch jSch = new JSch();
    Session session = jSch.getSession(executeInfo.get("user").toString(), executeInfo.get("host").toString(), Integer.parseInt(executeInfo.get("port").toString()));
    session.setPassword(executeInfo.get("pwd").toString());
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(30000);
    return session;
  }

  public static void main(String[] args) {
    Map<String,Object> executeInfo=new HashMap<>();
//    executeInfo.put("host","");
//    executeInfo.put("user","");
//    executeInfo.put("pwd","");
//    executeInfo.put("port",22);
    executeInfo.put("command","cd /; ls; pwd; cd data; ls; pwd;");
    Map<String,Object> exec = exec(executeInfo);
    System.out.println(exec);
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

plenilune-望月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值