java use remote link jsch linux command execution

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 use remote link jsch linux command execution
  • @author myz
  • */
    public class JSchUtil {
    private static JSch jsch;
    private static Session session;

    /**

    • First, connect to the server
    • @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();
      }

    /**

    • After connecting to the server executes the corresponding command 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); // returns the print result log
      }
      }
      } the catch (IOException E) {
      e.printStackTrace ();
      } the catch (JSchException E) {
      e.printStackTrace ();
      } // Finally the finally { and close the flow connection of
      the try {
      reader.Close ();
      } the catch (IOException E) {
      e.printStackTrace ();
      }
      channel.disconnect ();
      Session.disconnect ();
      }
      }

}

Guess you like

Origin blog.51cto.com/6272379/2420784