feat: capture output and exit code of commands

+ ignore interactive commands like vim, top or nano
This commit is contained in:
wancat committed 2023-07-27 17:56:32 +08:00
1 parent d997a061a9
commit b9643e7d5c
4 files changed
+25 -5

No files matched your search

+2 -1
View File
@@ -2,7 +2,8 @@ FROM ubuntu:latest
RUN apt-get update && apt-get install -y \
curl \
vim
vim \
jq
RUN adduser --disabled-password --gecos '' rudeus
+17 -3
View File
@@ -4,12 +4,26 @@ preexec() {
[ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # do nothing if completing
local command="$BASH_COMMAND"
local pwd="$PWD"
if [[ $command =~ ^(vim|top|less|more|nano) ]]; then
local payload=$(printf '{"token": "%s", "pwd": "%s", "command": "%s"}' "$TOKEN" "$pwd" "$command")
curl -X POST $API_ENDPOINT/api/v1/commands -H 'accept: */*' -H 'Content-Type: application/json' -d "$payload"
return
fi
# Execute the command, capture output and exit code
local output=$( { eval $command 2>&1; echo $? > /tmp/exit_code; })
local exit_code=$(cat /tmp/exit_code)
local output_esc=$(echo $output | jq -Rs .)
# Store command in variable
local cmd=$(printf '{"token": "%s", "pwd": "%s", "command": "%s"}' "$TOKEN" "$pwd" "$command")
local payload=$(printf '{"token": "%s", "pwd": "%s", "command": "%s", "exit_code": "%s", "output": %s}' "$TOKEN" "$pwd" "$command" "$exit_code" "$output_esc")
# Send command to the API
curl -X POST $API_ENDPOINT/api/v1/commands -H 'accept: */*' -H 'Content-Type: application/json' -d "$cmd"
curl -X POST $API_ENDPOINT/api/v1/commands -H 'accept: */*' -H 'Content-Type: application/json' -d "$payload" || echo $payload
BASH_COMMAND=""
}
# Install the trap
@@ -5,7 +5,7 @@ import { verifySessionJWT } from '../../utils/auth.js'
export async function newCommand(req, res) {
console.log('new command:', req.body)
const { token, command, pwd, output } = req.body
const { token, command, pwd, exit_code, output } = req.body
let sessionId
try {
@@ -27,6 +27,7 @@ export async function newCommand(req, res) {
session,
command,
pwd,
exit_code,
output,
})
+4
View File
@@ -17,6 +17,10 @@ const Command = model(
type: String,
required: true,
},
exit_code: {
type: Number,
required: false,
},
output: {
type: String,
required: false,