560cbf280e
Conjunto completo de funciones SSH para operaciones remotas: conexión, verificación de host, ejecución de comandos, transferencia de archivos (upload/download) y gestión de túneles. Incluye tipo SSHConn y tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
40 lines
1000 B
Go
40 lines
1000 B
Go
package infra
|
|
|
|
import (
|
|
"os/exec"
|
|
)
|
|
|
|
// SSHExec ejecuta un comando en el host remoto via SSH y retorna stdout, stderr y exit code.
|
|
func SSHExec(conn SSHConn, command string) (string, string, int, error) {
|
|
args := conn.sshArgs()
|
|
args = append(args, "-o", "BatchMode=yes")
|
|
args = append(args, conn.destination(), command)
|
|
|
|
cmd := exec.Command("ssh", args...)
|
|
var stdout, stderr []byte
|
|
cmd.Stdout = writerFunc(func(p []byte) (int, error) {
|
|
stdout = append(stdout, p...)
|
|
return len(p), nil
|
|
})
|
|
cmd.Stderr = writerFunc(func(p []byte) (int, error) {
|
|
stderr = append(stderr, p...)
|
|
return len(p), nil
|
|
})
|
|
|
|
err := cmd.Run()
|
|
exitCode := 0
|
|
if err != nil {
|
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
|
exitCode = exitErr.ExitCode()
|
|
} else {
|
|
return "", "", -1, err
|
|
}
|
|
}
|
|
return string(stdout), string(stderr), exitCode, nil
|
|
}
|
|
|
|
// writerFunc adapta una funcion a io.Writer.
|
|
type writerFunc func([]byte) (int, error)
|
|
|
|
func (f writerFunc) Write(p []byte) (int, error) { return f(p) }
|