I’m simulating a windows terminal with golang.
And I want it to be exactly same with real windows terminal window just like I’m executing a .bat file. But what I’m struggling with is to get the prompt string and print from cmd process.
Here’s my current code.
package minion_core
import (
"bufio"
"fmt"
"os/exec"
"strings"
"syscall"
"time"
)
var TestMode = true
func Test() {
// Start a new command prompt process
cmd := exec.Command("cmd.exe")
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
// Create pipes for standard input and output
stdin, err := cmd.StdinPipe()
if err != nil {
fmt.Println("Error creating stdin pipe:", err)
return
}
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println("Error creating stdout pipe:", err)
return
}
// Start the command
if err := cmd.Start(); err != nil {
fmt.Println("Error starting command:", err)
return
}
// Create a scanner to read the output
scanner := bufio.NewScanner(stdout)
// Variable to hold command output
var output strings.Builder
// Start a goroutine to read the command output
go func() {
for scanner.Scan() {
fmt.Println("⚡ " + scanner.Text() + "\n")
}
}()
// Function to execute commands
executeCommand := func(command string) {
_, err := stdin.Write([]byte(command + "\n"))
if err != nil {
fmt.Println("Error writing to stdin:", err)
}
// Wait a moment to ensure the output is captured
time.Sleep(1 * time.Second)
// Print the current output after executing the command
fmt.Println("Command output:\n", output.String())
// Clear the output for the next command
output.Reset()
}
// Execute several commands
executeCommand("echo Hello, World!")
executeCommand("dir")
executeCommand("nslookup")
executeCommand("google.com")
executeCommand("exit")
executeCommand("cd ..")
executeCommand("cd ..")
executeCommand("exit") // Exit the command prompt (optional)
// Close the stdin pipe
stdin.Close()
// Wait for the command to finish
if err := cmd.Wait(); err != nil {
fmt.Println("Error waiting for command:", err)
return
}
}
As you see, I executed commands one by one with a second interval. But I have no idea how to print the actual prompt of cmd instead of .
Please help me if you know the way to handle it.