温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java使用jsch远程链接linux执行命令

发布时间:2020-07-07 10:52:15 来源:网络 阅读:524 作者:myzczx 栏目:编程语言

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**

  • java 使用jsch远程链接linux 执行命令
  • @author myz
  • */
    public class JSchUtil {
    private static JSch jsch;
    private static Session session;

    /**

    • 首先连接服务器
    • @param user
    • @param passwd
    • @param host
    • @throws JSchException
      */
      public static void connect(String user, String passwd, String host) throws JSchException {
      jsch = new JSch();
      session = jsch.getSession(user, host, 22);
      session.setPassword(passwd);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);

      session.connect();
      }

    /**

    • 连接服务器后执行相应的linux命令
    • @param command
    • @param user
    • @param passwd
    • @param host
    • @throws JSchException
      */
      public static void execCmd(String command, String user, String passwd, String host) throws JSchException {
      connect(user, passwd, host);
      BufferedReader reader = null;
      Channel channel = null;
      try {
      while (command != null) {
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      channel.setInputStream(null);
      ((ChannelExec) channel).setErrStream(System.err);
      channel.connect();
      //获取流
      InputStream in = channel.getInputStream();
      reader = new BufferedReader(new InputStreamReader(in));
      String buf = null;
      while ((buf = reader.readLine()) != null) {
      System.out.println(buf);//打印返回的结果日志
      }
      }
      } catch (IOException e) {
      e.printStackTrace();
      } catch (JSchException e) {
      e.printStackTrace();
      } finally {//最后流和连接的关闭
      try {
      reader.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      channel.disconnect();
      session.disconnect();
      }
      }

}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI