通过Java实现bash命令过程解析
作者:龙凌云端 时间:2023-01-07 17:38:25
这篇文章主要介绍了通过Java实现bash命令过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、BASH 命令简介
Bash,Unix shell的一种,在1987年由布莱恩·福克斯为了GNU计划而编写。 * 发布第一个正式版本,原先是计划用在GNU操作系统上,但能运行于大多数类Unix系统的操作系统之上,包括Linux与Mac OS X v10.4都将它作为默认shell。
Bash是Bourne shell的后继兼容版本与开放源代码版本,它的名称来自Bourne shell(sh)的一个双关语(Bourne again / born again):Bourne-Again SHell。
Bash是一个命令处理器,通常运行于文本窗口中,并能执行用户直接输入的命令。Bash还能从文件中读取命令,这样的文件称为脚本。和其他Unix shell 一样,它支持文件名替换(通配符匹配)、管道、here文档、命令替换、变量,以及条件判断和循环遍历的结构控制语句。包括关键字、语法在内的基本特性全部是从sh借鉴过来的。其他特性,例如历史命令,是从csh和ksh借鉴而来。总的来说,Bash虽然是一个满足POSIX规范的shell,但有很多扩展。
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>
来源:https://www.cnblogs.com/miracle-luna/p/12050728.html
标签:Java,实现,bash,命令
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
DevExpress实现GridControl根据列选中一行
2021-08-16 05:23:19
java实现五子棋小游戏
2021-12-25 06:58:56
![](https://img.aspxhome.com/file/2023/0/63380_0s.jpg)
Android仿支付宝手势密码解锁功能
2023-02-14 09:06:46
![](https://img.aspxhome.com/file/2023/8/137888_0s.gif)
Android 和 windows C/C++/QT通讯时字节存储
2022-07-16 06:09:02
Android实现列表时间轴
2021-10-19 12:55:04
![](https://img.aspxhome.com/file/2023/4/126674_0s.jpg)
Mybatis逆工程jar包的修改和打包
2023-06-03 09:28:14
![](https://img.aspxhome.com/file/2023/7/119127_0s.png)
详解Spring中bean的几种注入方式
2023-02-12 20:25:07
Java如何基于ProcessBuilder类调用外部程序
2023-11-27 20:19:57
![](https://img.aspxhome.com/file/2023/0/59210_0s.png)
Mybatis如何通过接口实现sql执行原理解析
2022-11-30 11:31:26
![](https://img.aspxhome.com/file/2023/0/60480_0s.jpg)
Ajax 验证用户输入的验证码是否与随机生成的一致
2022-06-29 00:43:32
spring aop注解配置代码实例
2022-02-16 21:13:33
SpringBoot自定义maven-plugin插件整合asm代码插桩
2021-05-24 02:15:49
Kotlin Flow常见场景下的使用实例
2023-01-30 10:46:25
![](https://img.aspxhome.com/file/2023/5/116035_0s.jpg)
Java 常量池的实例详解
2023-12-04 00:51:28
Spring Security配置保姆级教程
2023-11-07 11:46:56
C# 扩展方法的使用
2022-04-05 14:46:24
![](https://img.aspxhome.com/file/2023/8/96318_0s.png)
在WPF中实现平滑滚动的方法详解
2021-06-17 06:34:16
C#处理猜拳问题的简单实例(非窗体)
2021-08-01 18:58:22
C#使用base64对字符串进行编码和解码的测试
2022-09-21 23:08:59
![](https://img.aspxhome.com/file/2023/2/78112_0s.png)
Java深入浅出讲解String类常见方法
2021-05-28 06:56:20
![](https://img.aspxhome.com/file/2023/6/91726_0s.png)