Fix issue with shell commands containing "<>" and unecessary (and poor) escaping
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
IamTheFij 2020-01-07 10:37:53 -08:00
parent 0269ad3512
commit 3226be69e7
3 changed files with 3 additions and 13 deletions

View File

@ -41,7 +41,7 @@ func TestMultiLineConfig(t *testing.T) {
log.Println("-----") log.Println("-----")
log.Println("TestMultiLineConfig(parse > string)") log.Println("TestMultiLineConfig(parse > string)")
expected := "echo 'Some string with stuff'; echo '<angle brackets>'; exit 1\n" expected := "echo 'Some string with stuff'; echo \"<angle brackets>\"; exit 1\n"
actual := config.Monitors[0].CommandShell actual := config.Monitors[0].CommandShell
if expected != actual { if expected != actual {
t.Errorf("TestMultiLineConfig(>) failed") t.Errorf("TestMultiLineConfig(>) failed")

View File

@ -5,7 +5,7 @@ monitors:
- name: Shell - name: Shell
command_shell: > command_shell: >
echo 'Some string with stuff'; echo 'Some string with stuff';
echo '<angle brackets>'; echo "<angle brackets>";
exit 1 exit 1
alert_down: ['log_shell'] alert_down: ['log_shell']
alert_after: 1 alert_after: 1

12
util.go
View File

@ -5,19 +5,9 @@ import (
"strings" "strings"
) )
// escapeCommandShell accepts a command to be executed by a shell and escapes it
func escapeCommandShell(command string) string {
// Remove extra spaces and newlines from ends
command = strings.TrimSpace(command)
// TODO: Not sure if this part is actually needed. Should verify
// Escape double quotes since this will be passed in as an argument
command = strings.Replace(command, `"`, `\"`, -1)
return command
}
// ShellCommand takes a string and executes it as a command using `sh` // ShellCommand takes a string and executes it as a command using `sh`
func ShellCommand(command string) *exec.Cmd { func ShellCommand(command string) *exec.Cmd {
shellCommand := []string{"sh", "-c", escapeCommandShell(command)} shellCommand := []string{"sh", "-c", strings.TrimSpace(command)}
//log.Printf("Shell command: %v", shellCommand) //log.Printf("Shell command: %v", shellCommand)
return exec.Command(shellCommand[0], shellCommand[1:]...) return exec.Command(shellCommand[0], shellCommand[1:]...)
} }