Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the parsing of bash command process through Java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to achieve bash command process parsing through Java, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Brief introduction of BASH command

A type of Bash,Unix shell, written by Brian Fox for the GNU project in 1987. The first official version released in 1989 was originally intended for use on the GNU operating system, but it can run on most Unix-like operating systems, including Linux and Mac OS X v10.4 as the default shell.

Bash is the subsequent compatible and open source version of Bourne shell, and its name comes from a pun (Bourne again/ born again) of Bourne shell (sh): Bourne-AgainSHell.

Bash is a command processor that usually runs in a text window and executes commands entered directly by the user. Bash can also read commands from files, which are called scripts. Like other Unix shell, it supports file name substitution (wildcard matching), pipes, here documents, command substitution, variables, and structural control statements for conditional judgment and loop traversal. The basic features, including keywords and grammar, are all borrowed from sh. Other features, such as historical commands, are borrowed from csh and ksh. In general, Bash is a shell that meets the POSIX specification, but it has many extensions.

2. Java implements BASH command to execute Shell script

1) the code is implemented as follows:

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 }} / * create connection and authenticate * @ 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 }} / * close connection * / public void close () {try {conn.close (); conn = null;} catch (Exception e) {e.printStackTrace () Execute the shell command * @ 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"; / / here, according to the actual situation, replace the host to which you need to visit 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 ("the result of execution is as follows:\ n" + result.toString ());}}

2) the implementation results are as follows:

The result of the execution is as follows: / home/miracleluna.txtHello, Ichimm SshUtil.Nice to meet you.^ _ ^

3) the pom.xml reference dependency package is as follows:

Org.slf4j slf4j-api 1.7.21 ch.ethz.ganymed ganymed-ssh3 262 is all the contents of this article "how to implement bash command process parsing through Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report