This would be a great solution but I am trying to find a way to show the progress time of the terminal command execution.
So right now, I found a way of gathering the execution time of the terminal command I’m trying to use.
When I click the html button, it executes the following terminal command:
sudo nmap -F -sS X.X.X.0/24 --stats-every 2s | grep --line-buffered ‘Ping Scan Timing’ | awk ‘{print $5}’
This outputs the execution time of the command every 2s to my os.stdout terminal. The output looks something like this:
10%
15%
30%
.
.
.
But now I have modified my code because I am trying to redirect this output to my webpage, and render it in realtime, so that it I can see how much progress is left for the execution to be completed since this command can take a while to load.
The problem I am running into is that I cannot properly use the stdoutpipe function to redirect the output to my webpage. Here is a snippet of my code for the handler that gets triggered when I click the button in my webpage:
func viewHandler(w http.ResponseWriter, r *http.Request) {
conn, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Oops", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
nmap_chain := "nmap -F -sS X.X.X.0/24 -oX output.xml --stats-every 2s | grep --line-buffered 'Ping Scan Timing' | awk '{print $5}'"
cmd := exec.Command("bash","-c",nmap_chain)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
in := bufio.NewScanner(stdout)
for in.Scan() {
fmt.Fprintf(w,"%d\n\n",in)
conn.Flush()
time.Sleep(time.Second)
}
if err := in.Err(); err != nil {
log.Printf("error: %s", err)
}
}
My html file looks like the following as well:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>NMAP Demo</title>
<link rel="stylesheet" type="text/css" href="layout/mystyle.css">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#exec").on("click", function() {
$('#exec').prop('disabled', true);
$.ajax({
url: "/exec",
method: "GET",
success: function(data) {
$("#response").html(data);
$('#exec').prop('disabled', false);
},
});
});
});
</script>
</head>
<body>
<div id="headerBar"></div>
<div>
<button id="exec">Execute Command</button>
</div>
<div id="results">
<textarea readonly id="response" rows="50" cols="50" style="resize"></textarea>
</div>
</body>
</html>
Right now I cannot see any output in my html textarea when this handler is executed. I’ve also tried creating a basic function that would execute the nmap command mentioned, and redirect the output to a log instead of os.stdout using stdoutpipe. But still I cannot see any output.
Any suggestions would be helpful.
Thanks,