如何通过Java实现bash命令过程解析
创始人
2024-12-20 10:41:52
0次

1、BASH 命令简介

Bash,Unix shell的一种,在1987年由布莱恩·福克斯为了GNU计划而编写。1989年发布第一个正式版本,原先是计划用在GNU操作系统上,但能运行于大多数类Unix系统的操作系统之上,包括Linux与Mac OS X v10.4都将它作为默认shell。

Bash是Bourne shell的后继兼容版本与开放源代码版本,它的名称来自Bourne shell(sh)的一个双关语(Bourne again/ born again):Bourne-AgainSHell。

Bash是一个命令处理器,通常运行于文本窗口中,并能执行用户直接输入的命令。Bash还能从文件中读取命令,这样的文件称为脚本。和其他Unix shell 一样,它支持文件名替换(通配符匹配)、管道、here文档、命令替换、变量,以及条件判断和循环遍历的结构控制语句。包括关键字、语法在内的基本特性全部是从sh借鉴过来的。其他特性,例如历史命令,是从csh和ksh借鉴而来。总的来说,Bash虽然是一个满足POSIX规范的shell,但有很多扩展。

2、Java实现 BASH命令执行Shell脚本

1)代码实现如下:

import ch.ethz.ssh3.Connection;import ch.ethz.ssh3.Session;import ch.ethz.ssh3.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 command(String command) {    if (conn == null && !connection()) {      logger.error("Authentication failed.");      return null;    }    List result = new ArrayList();    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 resultList = bashUtil.command(command);    StringBuffer result = new StringBuffer("");    resultList.forEach(str -> result.append(str + "\n"));    System.out.println("执行的结果如下: \n" + result.toString());  }}

2)执行结果如下:

执行的结果如下:/home/miracleluna.txtHello, I'm SshUtil.Nice to meet you.^_^

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

          org.slf4j      slf4j-api      1.7.21                  ch.ethz.ganymed      ganymed-ssh3      262    

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...