Files
move-data-nas/internal/sshmanager/testconn.go
T
darroyo bc3bc44c4a Add shutdown machine feature with configurable command
Backend:
- New migration: add shutdown_command TEXT column to machines table
- Machine model updated with ShutdownCommand field (Create/GetAll/GetByID/Update)
- MachineRequest/MachineResponse DTOs updated with shutdown_command field
- New ShutdownResponse DTO
- New POST /api/machines/{id}/shutdown handler via SSH
- Refactor sshmanager/testconn.go: extract dialSSH() helper shared with shutdown.go
- New sshmanager/shutdown.go: RunRemoteCommand with 15s timeout

Frontend:
- New shutdownMachine() API helper and ShutdownResponse type in client.ts
- New shutdown_command field in MachineForm
- Power button (amber) in machines table actions
- Shutdown confirmation modal with WoL warning notice
- shutdown_command input field in machine edit/create form
- Machine interface updated with shutdown_command and last_seen_at fields
2026-07-13 10:02:18 -04:00

116 lines
3.1 KiB
Go

package sshmanager
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
type ConnResult struct {
Success bool
Output string
Error string
Fingerprint string
}
func dialSSH(ctx context.Context, host string, port int, user, privKeyPath, knownHostsPath string, strictHostKeyChecking bool) (*ssh.Client, string, error) {
addr := fmt.Sprintf("%s:%d", host, port)
auths := []ssh.AuthMethod{}
if privKeyPath != "" {
key, err := os.ReadFile(privKeyPath)
if err != nil {
return nil, "", fmt.Errorf("reading private key: %w", err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, "", fmt.Errorf("parsing private key: %w", err)
}
auths = append(auths, ssh.PublicKeys(signer))
}
var capturedFingerprint string
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
h := sha256.Sum256(key.Marshal())
capturedFingerprint = "SHA256:" + base64.RawStdEncoding.EncodeToString(h[:])
if strictHostKeyChecking && knownHostsPath != "" {
kh, err := GetKnownHost(filepath.Dir(knownHostsPath), host, port)
if err != nil {
return fmt.Errorf("checking known_hosts: %w", err)
}
if kh == nil {
return fmt.Errorf("host key not found in known_hosts: %s", hostname)
}
wantFP := kh.Fingerprint
if capturedFingerprint != wantFP {
return fmt.Errorf("host key mismatch: got %s, want %s", capturedFingerprint, wantFP)
}
}
return nil
}
cfg := &ssh.ClientConfig{
User: user,
Auth: auths,
HostKeyCallback: hostKeyCallback,
Timeout: 10 * time.Second,
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
conn, err := ssh.Dial("tcp", addr, cfg)
if err != nil {
if strings.Contains(err.Error(), "known_hosts") || strings.Contains(err.Error(), "host key") {
return nil, capturedFingerprint, fmt.Errorf("host key verification failed: %v", err)
}
return nil, capturedFingerprint, fmt.Errorf("connection failed: %v", err)
}
return conn, capturedFingerprint, nil
}
func TestSSHConnection(ctx context.Context, host string, port int, user, privKeyPath, knownHostsPath string, strictHostKeyChecking bool) (*ConnResult, error) {
conn, fingerprint, err := dialSSH(ctx, host, port, user, privKeyPath, knownHostsPath, strictHostKeyChecking)
if err != nil {
return &ConnResult{
Success: false,
Error: err.Error(),
Fingerprint: fingerprint,
}, nil
}
defer conn.Close()
session, err := conn.NewSession()
if err != nil {
return &ConnResult{Success: false, Error: fmt.Sprintf("session: %v", err), Fingerprint: fingerprint}, nil
}
defer session.Close()
var stdout, stderr bytes.Buffer
session.Stdout = &stdout
session.Stderr = &stderr
if err := session.Run("echo ok && uname -a"); err != nil {
return &ConnResult{
Success: false,
Error: fmt.Sprintf("exec: %v, stderr: %s", err, stderr.String()),
Fingerprint: fingerprint,
}, nil
}
return &ConnResult{
Success: true,
Output: stdout.String(),
Fingerprint: fingerprint,
}, nil
}