Java 实现 bash命令
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借鉴过来的。其他特性,例如历史命令,是从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>
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)