gosync/tools/ssh.go

56 lines
1.2 KiB
Go

package tools
import (
"errors"
"io"
"os/exec"
"strings"
"velvettear/gosync/settings"
)
// exported function(s)
func TestConnection() error {
var remote string
if settings.SourceIsRemote() {
remote, _, _ = strings.Cut(settings.Target, ":")
} else if settings.TargetIsRemote() {
remote, _, _ = strings.Cut(settings.Target, ":")
} else {
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 {
remote = settings.User + "@" + remote
}
arguments = append(arguments, remote, "'exit'")
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
}