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借鑒過來的。其他特性,例如歷史命令,是從 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM