java远程连接Linux执行命令的三种方式

2024-04-14 5537阅读

java远程连接Linux执行命令的三种方式

  • 1. 使用JDK自带的RunTime类和Process类实现
  • 2. ganymed-ssh2 实现
  • 3. jsch实现
  • 4. 完整代码:
    • 执行shell命令
    • 下载和上传文件

      1. 使用JDK自带的RunTime类和Process类实现

      public static void main(String[] args){
          Process proc = RunTime.getRunTime().exec("cd /home/tom; ls;")
          // 标准输入流(必须写在 waitFor 之前)
          String inStr = consumeInputStream(proc.getInputStream());
          // 标准错误流(必须写在 waitFor 之前)
          String errStr = consumeInputStream(proc.getErrorStream());
          int retCode = proc.waitFor();
          if(retCode == 0){
              System.out.println("程序正常执行结束");
          }
      }
      /**
       *   消费inputstream,并返回
       */
      public static String consumeInputStream(InputStream is){
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
          String s ;
          StringBuilder sb = new StringBuilder();
          while((s=br.readLine())!=null){
              System.out.println(s);
              sb.append(s);
          }
          return sb.toString();
      }
      

      2. ganymed-ssh2 实现

      pom

      java远程连接Linux执行命令的三种方式 第1张
      ()
      
          ch.ethz.ganymed
          ganymed-ssh2
          build210
      
      
      import ch.ethz.ssh2.Connection;
      import ch.ethz.ssh2.Session;
      public static void main(String[] args){
          String host = "210.38.162.181";
          int port = 22;
          String username = "root";
          String password = "root";
          // 创建连接
          Connection conn = new Connection(host, port);
          // 启动连接
          conn.connection();
          // 验证用户密码
          conn.authenticateWithPassword(username, password);
          Session session = conn.openSession();
          session.execCommand("cd /home/winnie; ls;");
          
          // 消费所有输入流
          String inStr = consumeInputStream(session.getStdout());
          String errStr = consumeInputStream(session.getStderr());
          
          session.close;
          conn.close();
      }
      /**
       *   消费inputstream,并返回
       */
      public static String consumeInputStream(InputStream is){
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
          String s ;
          StringBuilder sb = new StringBuilder();
          while((s=br.readLine())!=null){
              System.out.println(s);
              sb.append(s);
          }
          return sb.toString();
      }
      

      3. jsch实现

      pom

          com.jcraft
          jsch
          0.1.55
      
      
      import com.jcraft.jsch.JSch;
      import com.jcraft.jsch.Session;
      public static void main(String[] args){
          String host = "210.38.162.181";
          int port = 22;
          String username = "root";
          String password = "root";
          // 创建JSch
          JSch jSch = new JSch();
          // 获取session
          Session session = jSch.getSession(username, host, port);
          session.setPassword(password);
          Properties prop = new Properties();
          prop.put("StrictHostKeyChecking", "no");
          session.setProperties(prop);
          // 启动连接
          session.connect();
          ChannelExec exec = (ChannelExec)session.openChannel("exec");
          exec.setCommand("cd /home/winnie; ls;");
          exec.setInputStream(null);
          exec.setErrStream(System.err);
          exec.connect();
         
          // 消费所有输入流,必须在exec之后
          String inStr = consumeInputStream(exec.getInputStream());
          String errStr = consumeInputStream(exec.getErrStream());
          
          exec.disconnect();
          session.disconnect();
      }
      /**
       *   消费inputstream,并返回
       */
      public static String consumeInputStream(InputStream is){
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
          String s ;
          StringBuilder sb = new StringBuilder();
          while((s=br.readLine())!=null){
              System.out.println(s);
              sb.append(s);
          }
          return sb.toString();
      }
      

      4. 完整代码:

      执行shell命令

          commons-io
          commons-io
          2.6
      
      
          com.jcraft
          jsch
          0.1.55
      
      
          ch.ethz.ganymed
          ganymed-ssh2
          build210
      
      
      import cn.hutool.core.io.IoUtil;
      import com.jcraft.jsch.ChannelShell;
      import com.jcraft.jsch.JSch;
      import com.jcraft.jsch.Session;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.io.PrintWriter;
      import java.util.Vector;
      /**
       * shell脚本调用类
       *
       * @author Micky
       */
      public class SshUtil {
          private static final Logger logger = LoggerFactory.getLogger(SshUtil.class);
          private Vector stdout;
          // 会话session
          Session session;
          //输入IP、端口、用户名和密码,连接远程服务器
          public SshUtil(final String ipAddress, final String username, final String password, int port) {
              try {
                  JSch jsch = new JSch();
                  session = jsch.getSession(username, ipAddress, port);
                  session.setPassword(password);
                  session.setConfig("StrictHostKeyChecking", "no");
                  session.connect(100000);
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
          public int execute(final String command) {
              int returnCode = 0;
              ChannelShell channel = null;
              PrintWriter printWriter = null;
              BufferedReader input = null;
              stdout = new Vector();
              try {
                  channel = (ChannelShell) session.openChannel("shell");
                  channel.connect();
                  input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
                  printWriter = new PrintWriter(channel.getOutputStream());
                  printWriter.println(command);
                  printWriter.println("exit");
                  printWriter.flush();
                  logger.info("The remote command is: ");
                  String line;
                  while ((line = input.readLine()) != null) {
                      stdout.add(line);
                      System.out.println(line);
                  }
              } catch (Exception e) {
                  e.printStackTrace();
                  return -1;
              }finally {
                  IoUtil.close(printWriter);
                  IoUtil.close(input);
                  if (channel != null) {
                      channel.disconnect();
                  }
              }
              return returnCode;
          }
          // 断开连接
          public void close(){
              if (session != null) {
                  session.disconnect();
              }
          }
          // 执行命令获取执行结果
          public String executeForResult(String command) {
              execute(command);
              StringBuilder sb = new StringBuilder();
              for (String str : stdout) {
                  sb.append(str);
              }
              return sb.toString();
          }
          public static void main(String[] args) {
          	String cmd = "ls /opt/";
              SshUtil execute = new SshUtil("XXX","abc","XXX",22);
              // 执行命令
              String result = execute.executeForResult(cmd);
              System.out.println(result);
              execute.close();
          }
      }
      

      下载和上传文件

      /**
       * 下载和上传文件
       */
      public class ScpClientUtil {
          private String ip;
          private int port;
          private String username;
          private String password;
          static private ScpClientUtil instance;
          static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String passward) {
              if (instance == null) {
                  instance = new ScpClientUtil(ip, port, username, passward);
              }
              return instance;
          }
          public ScpClientUtil(String ip, int port, String username, String passward) {
              this.ip = ip;
              this.port = port;
              this.username = username;
              this.password = passward;
          }
          public void getFile(String remoteFile, String localTargetDirectory) {
              Connection conn = new Connection(ip, port);
              try {
                  conn.connect();
                  boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                  if (!isAuthenticated) {
                      System.err.println("authentication failed");
                  }
                  SCPClient client = new SCPClient(conn);
                  client.get(remoteFile, localTargetDirectory);
              } catch (IOException ex) {
                  ex.printStackTrace();
              }finally{
                  conn.close();
              }
          }
          public void putFile(String localFile, String remoteTargetDirectory) {
              putFile(localFile, null, remoteTargetDirectory);
          }
          public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
              putFile(localFile, remoteFileName, remoteTargetDirectory,null);
          }
          public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
              Connection conn = new Connection(ip, port);
              try {
                  conn.connect();
                  boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                  if (!isAuthenticated) {
                      System.err.println("authentication failed");
                  }
                  SCPClient client = new SCPClient(conn);
                  if ((mode == null) || (mode.length() == 0)) {
                      mode = "0600";
                  }
                  if (remoteFileName == null) {
                      client.put(localFile, remoteTargetDirectory);
                  } else {
                      client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
                  }
              } catch (IOException ex) {
                  ex.printStackTrace();
              }finally{
                  conn.close();
              }
          }
          public static void main(String[] args) {
              ScpClientUtil scpClient = ScpClientUtil.getInstance("XXX", 22, "XXX", "XXX");
              // 从远程服务器/opt下的index.html下载到本地项目根路径下
              scpClient.getFile("/opt/index.html","./");
             // 把本地项目下根路径下的index.html上传到远程服务器/opt目录下
              scpClient.putFile("./index.html","/opt");
          }
      }
      
      java远程连接Linux执行命令的三种方式 第2张
      ()

    免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

    目录[+]