2023-09-07 15:20:19 +02:00
|
|
|
package tools
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
"velvettear/gosync/settings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// exported function(s)
|
|
|
|
func TestConnection() error {
|
2023-09-22 10:54:10 +02:00
|
|
|
var remote string
|
|
|
|
if settings.SourceIsRemote() {
|
2023-09-22 15:50:03 +02:00
|
|
|
remote, _, _ = strings.Cut(settings.Source, ":")
|
2023-09-22 10:54:10 +02:00
|
|
|
} else if settings.TargetIsRemote() {
|
|
|
|
remote, _, _ = strings.Cut(settings.Target, ":")
|
|
|
|
} else {
|
2023-09-07 15:20:19 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var arguments []string
|
|
|
|
if len(settings.Password) > 0 {
|
|
|
|
arguments = append(arguments, "-p", settings.Password)
|
|
|
|
}
|
|
|
|
arguments = append(arguments, "ssh")
|
|
|
|
if len(settings.User) > 0 {
|
2023-09-22 10:54:10 +02:00
|
|
|
remote = settings.User + "@" + remote
|
2023-09-07 15:20:19 +02:00
|
|
|
}
|
2023-09-22 15:50:03 +02:00
|
|
|
arguments = append(arguments, remote, "exit")
|
2023-09-07 15:20:19 +02:00
|
|
|
cmd := exec.Command("sshpass", arguments...)
|
|
|
|
stdout, stdoutError := cmd.StdoutPipe()
|
|
|
|
stderr, stderrError := cmd.StderrPipe()
|
|
|
|
cmd.Start()
|
|
|
|
if stdoutError != nil {
|
|
|
|
return stdoutError
|
|
|
|
}
|
|
|
|
if stderrError != nil {
|
|
|
|
return stderrError
|
|
|
|
}
|
|
|
|
_, stdoutError = io.ReadAll(stdout)
|
|
|
|
if stdoutError != nil {
|
|
|
|
return stdoutError
|
|
|
|
}
|
|
|
|
errorBytes, stderrError := io.ReadAll(stderr)
|
|
|
|
if stderrError != nil {
|
|
|
|
return stderrError
|
|
|
|
}
|
|
|
|
cmd.Wait()
|
|
|
|
error := strings.TrimSpace(string(errorBytes))
|
|
|
|
if len(error) > 0 {
|
|
|
|
return errors.New(error)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|