Untitled

 avatar
unknown
plain_text
2 years ago
2.3 kB
3
Indexable
import expect4j.Expect4j;
import expect4j.ExpectUtils;
import expect4j.matches.Match;
import expect4j.matches.RegExpMatch;

import java.io.IOException;

public class InteractiveTerminal {
    public static void main(String[] args) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash");
            Process process = processBuilder.start();

            // Tạo kết nối PTY
            Expect4j expect = new Expect4j(process.getInputStream(), process.getOutputStream());

            // Thêm lệnh vào terminal và đọc đầu ra
            sendCommand(expect, "echo Hello");
            String output1 = readOutput(expect);

            sendCommand(expect, "ls -l");
            String output2 = readOutput(expect);

            // In đầu ra của lệnh
            System.out.println("Output 1: " + output1);
            System.out.println("Output 2: " + output2);

            // Kết thúc kết nối
            expect.close();
            process.waitFor();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void sendCommand(Expect4j expect, String command) {
        try {
            // Gửi lệnh và đợi cho dấu nhắc của terminal
            boolean success = ExpectUtils.expect(expect, new Match[]{
                    new RegExpMatch(".*\\$.*"), // Đợi cho dấu nhắc của terminal
            }, command + "\r\n");

            if (!success) {
                System.out.println("Failed to send command: " + command);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String readOutput(Expect4j expect) {
        try {
            // Đọc đầu ra cho đến khi gặp dấu nhắc của terminal
            StringBuilder output = new StringBuilder();
            boolean success = ExpectUtils.expect(expect, new Match[]{
                    new RegExpMatch(".*\\$.*"), // Đợi cho dấu nhắc của terminal
            }, output);

            if (!success) {
                System.out.println("Failed to read output.");
            }

            return output.toString().trim();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
Editor is loading...
Leave a Comment