Java 实现 bash命令


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-Again SHell。
Bash是一个命令处理器,通常运行于文本窗口中,并能执行用户直接输入的命令。Bash还能从文件中读取命令,这样的文件称为脚本。和其他Unix shell 一样,它支持文件名替换(通配符匹配)、管道here文档、命令替换、变量,以及条件判断和循环遍历的结构控制语句。包括关键字、语法在内的基本特性全部是从sh借鉴过来的。其他特性,例如历史命令,是从cshksh借鉴而来。总的来说,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>

 PS:

Maven依赖jar包问题,请参考如下博文:

https://www.cnblogs.com/miracle-luna/p/11863679.html

Java 实现 bash命令
https://www.cnblogs.com/miracle-luna/p/12050728.html

Java 实现 ssh命令 登录主机执行shell命令
https://www.cnblogs.com/miracle-luna/p/12050367.html

Java 实现 telnet命令 验证主机端口的连通性
https://www.cnblogs.com/miracle-luna/p/12049658.html

Java 检查IPv6地址的合法性
https://www.cnblogs.com/miracle-luna/p/12041780.html

Java 实现判断 主机是否能 ping 通
https://www.cnblogs.com/miracle-luna/p/12026797.html

Java 实现 bash命令的更多相关文章

  1. Java 实现 ssh命令 登录主机执行shell命令

    Java 实现 ssh命令 登录主机执行shell命令 1.SSH命令 SSH 为 Secure Shell 的缩写,由 IETF 的网络小组(Network Working Group)所制定:SS ...

  2. Java 实现 telnet命令 验证主机端口的连通性

    Java 实现 telnet命令 验证主机端口的连通性 1.Telnet 命令 Telnet协议是TCP/IP协议族中的一员,是Internet远程登录服务的标准协议和主要方式.它为用户提供了在本地计 ...

  3. java 调用bash shell脚本阻塞的小问题的解决

    java  调用bash shell脚本阻塞的小问题的解决 背景 使用java实现的web端,web端相应用户的界面操作,使用java调用bash实现的shell脚本进行实际的操作,操作完成返回执行结 ...

  4. Linux常用bash命令

    目录 bash命令 基础操作 export | whereis | which | clear 文件操作 ls | touch | cat | more | head | tail | mv | cp ...

  5. Linux Bash命令总结

    Bash命令 一:man命令,是manual 手册的意思,如man ps表示查看ps命令的手册,man man查看man命令的手册:也可以通过man xx查看是否有xx命令. 二:cat命令,用来一次 ...

  6. java运行Linux命令

    <%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UT ...

  7. java 执行shell命令遇到的坑

    正常来说java调用shell命令就是用 String[] cmdAry = new String[]{"/bin/bash","-c",cmd} Runtim ...

  8. java与javac命令的功用

    一.javac用来编译java程序,比如说我写了一个Server.java文件,首先通过命令行进入.java文件所在的路径, 然后通过输入 javac Server.java 命令行来完成编译,编译之 ...

  9. Windows 10预览版14316开启Bash命令支持

    00x0 前言 4月7日凌晨,微软推送了最新的Windows 10一周年更新预览版14316,其中重要的是原生支持Linux Bash命令行支持. 00x1 问题 如何开启Linux Bash命令行? ...

随机推荐

  1. 使用pyinstaller打包使用cx_Oracle模块的程序出现The specified module could not be found的问题

    pyinstaller看起来并不会将动态链接库自动打包,所以我们需要告诉pyinstaller要打包哪些动态链接库,步骤如下(假设python文件名为 oracletest.py): 1. 使用pyi ...

  2. IdentityServer(二)客户端授权模式

    前言 客户端授权模,客户端直接向Identity Server申请token并访问资源.客户端授权模式比较适用于服务之间的通信. 搭建Identity服务 新建名为 IdentityServer 的W ...

  3. open_window()到底做了什么?

    Hlong MainWndID= (Hlong)m_hWnd; open_framegrabber(, , , , , , , , "default", , -, &Acq ...

  4. 如何查看float在内存中存储方式

    float fla = -1000; unsigned int *pfla = (unsigned int*)&fla; printf("fla=%X\n",*pfla); ...

  5. Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,IMPLICIT) for operation '<>'

    1.问题 今天又在mysql中遇到了,吐血. 2.解决方案 SQL最后加上 COLLATE utf8mb4_unicode_ci SELECT t2.cust_id as cust_id_ex,t1. ...

  6. 12、生命周期-@Bean指定初始化和销毁方法

    12.生命周期-@Bean指定初始化和销毁方法 Bean的生命周期:创建->初始化->销毁 容器管理bean的生命周期 我们可以自定义初始方法和销毁方法,容器在bean进行到当期那生命周期 ...

  7. 《剑指offer》数组中只出现一次的数字

    本题来自<剑指offer> 数组中只出现一次的数字 题目: 一个整型数组里除了两个数字之外,其他的数字都出现了两次.请写程序找出这两个只出现一次的数字. 思路: 思路一:在<剑指of ...

  8. read,write,lseek

    转自 http://blog.csdn.net/todd911/article/details/11237627 1.read 调用read函数从文件去读数据,函数定义如下: #include < ...

  9. CodeForces - 999B Reversing Encryption

    B - Reversing Encryption A string s of length n can be encrypted by the following algorithm: iterate ...

  10. 串结构练习——字符串连接(SDUT 2124)

    Problem Description 给定两个字符串string1和string2,将字符串string2连接在string1的后面,并将连接后的字符串输出. 连接后字符串长度不超过110. Inp ...