欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

通过Java实现bash命令过程解析

程序员文章站 2023-08-24 19:51:48
这篇文章主要介绍了通过java实现bash命令过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、bash 命令简介...

这篇文章主要介绍了通过java实现bash命令过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、bash 命令简介

2、java实现 bash命令执行shell脚本

1)代码实现如下:

import ch.ethz.ssh2.connection;
import ch.ethz.ssh2.session;
import ch.ethz.ssh2.streamgobbler;
import org.slf4j.logger;
import org.slf4j.loggerfactory;

import java.io.bufferedreader;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.util.arraylist;
import java.util.list;


public class bashutil {

  private logger logger = loggerfactory.getlogger(bashutil.class);

  private string hostname;

  private string username;

  private string password;

  private int port;

  private connection conn;

  private bashutil() {
  }

  public bashutil(string hostname, string username, string password) {
    this(hostname, username, password, 22);
  }

  public bashutil(string hostname, string username, string password, integer port) {
    this.hostname = hostname;
    this.username = username;
    this.password = password;
    if (port == null) {
      port = 22;
    } else {
      this.port = port;
    }
  }

  /**
   * 创建连接并认证
   * @return
   */
  public boolean connection() {
    try {
      conn = new connection(hostname, port);
      conn.connect();
      boolean isauthenticated = conn.authenticatewithpassword(username, password);
      return isauthenticated;
    } catch (exception e) {
      e.printstacktrace();
      return false;
    }
  }

  /**
   * 关闭连接
   */
  public void close() {
    try {
      conn.close();
      conn = null;
    } catch (exception e) {
      e.printstacktrace();
    }
  }

  /**
   * 执行shell命令
   * @param command
   * @return
   */
  public list<string> command(string command) {
    if (conn == null && !connection()) {
      logger.error("authentication failed.");
      return null;
    }
    list<string> result = new arraylist<string>();
    try {
      session sess = conn.opensession();
      sess.execcommand(command);
      inputstream stdout = new streamgobbler(sess.getstdout());
      inputstream stderr = new streamgobbler(sess.getstderr());
      bufferedreader br_out = new bufferedreader(new inputstreamreader(stdout, "utf-8"));
      bufferedreader br_err = new bufferedreader(new inputstreamreader(stderr, "utf-8"));
      stringbuffer sb_err = new stringbuffer();
      string line = null;
      while ((line = br_out.readline()) != null) {
        result.add(line.trim());
      }
      while ((line = br_err.readline()) != null) {
        sb_err.append(line + "\n");
      }
      if (isnotempty(sb_err.tostring())) {
        logger.error(sb_err.tostring());
        return null;
      }
      return result;
    } catch (exception e) {
      e.printstacktrace();
    }
    return null;
  }


  private static boolean isempty(string content) {
    if (content == null) {
      return true;
    } else {
      return "".equals(content.trim()) || "null".equalsignorecase(content.trim());
    }
  }

  private static boolean isnotempty(string content) {
    return !isempty(content);
  }

  public static void main(string[] args){
    string hostname = "192.168.123.234";  // 此处根据实际情况,换成自己需要访问的主机ip
    string username = "root";
    string password = "password";
    integer port = 22;
    string command = "cd /home/miracle&&pwd&&ls&&cat luna.txt";

    bashutil bashutil = new bashutil(hostname, username, password, port);
    list<string> resultlist = bashutil.command(command);
    stringbuffer result = new stringbuffer("");
    resultlist.foreach(str -> result.append(str + "\n"));

    system.out.println("执行的结果如下: \n" + result.tostring());
  }
}

2)执行结果如下:

执行的结果如下: 
/home/miracle
luna.txt
hello, i'm sshutil.
nice to meet you.^_^

3)pom.xml引用依赖包如下:

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupid>org.slf4j</groupid>
      <artifactid>slf4j-api</artifactid>
      <version>1.7.21</version>
    </dependency>


    <!-- ssh -->
    <dependency>
      <groupid>ch.ethz.ganymed</groupid>
      <artifactid>ganymed-ssh2</artifactid>
      <version>262</version>
    </dependency>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。