admin_backend/model/ssh.go
2025-02-11 15:35:38 +08:00

46 lines
828 B
Go

package model
import (
"backend/common"
"fmt"
"golang.org/x/crypto/ssh"
)
type SshClient struct {
client *ssh.Client
}
func NewSshClient(config *common.SshConfig) (*SshClient, error) {
sshconfig := &ssh.ClientConfig{
User: config.Username,
Auth: []ssh.AuthMethod{
ssh.Password(config.Password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
client, err := ssh.Dial("tcp", addr, sshconfig)
if err != nil {
return nil, err
}
return &SshClient{client: client}, nil
}
func (s *SshClient) RunCommand(cmd string) (string, error) {
session, err := s.client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
output, err := session.CombinedOutput(cmd)
if err != nil {
return "", err
}
return string(output), nil
}