FemaInstaller/internal/ssh/client.go

90 lines
2.1 KiB
Go

package ssh
import (
"fmt"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
// ClientConfig holds the configuration for SSH connections
type ClientConfig struct {
Host string
Port string
Username string
Password string
Timeout time.Duration
}
// NewClientConfig creates a new SSH client configuration
func NewClientConfig(host, port, username, password string) *ClientConfig {
return &ClientConfig{
Host: host,
Port: port,
Username: username,
Password: password,
Timeout: 30 * time.Second,
}
}
// CreateSSHClient creates and returns an SSH client using the provided configuration
func CreateSSHClient(config *ClientConfig) (*ssh.Client, error) {
if config == nil {
return nil, fmt.Errorf("SSH config cannot be nil")
}
sshConfig := &ssh.ClientConfig{
User: config.Username,
Auth: []ssh.AuthMethod{
ssh.Password(config.Password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: config.Timeout,
}
client, err := ssh.Dial("tcp", config.Host+":"+config.Port, sshConfig)
if err != nil {
return nil, fmt.Errorf("failed to connect to SSH server: %w", err)
}
return client, nil
}
// CreateSFTPClient creates and returns an SFTP client using the provided configuration
func CreateSFTPClient(config *ClientConfig) (*sftp.Client, error) {
if config == nil {
return nil, fmt.Errorf("SFTP config cannot be nil")
}
// Create SSH client
sshClient, err := CreateSSHClient(config)
if err != nil {
return nil, err
}
// Create SFTP client
sftpClient, err := sftp.NewClient(sshClient)
if err != nil {
sshClient.Close() // Close the SSH client in case of failure
return nil, fmt.Errorf("failed to create SFTP client: %w", err)
}
return sftpClient, nil
}
// ExecuteCommand executes a command on the remote server
func ExecuteCommand(client *ssh.Client, command string) error {
session, err := client.NewSession()
if err != nil {
return fmt.Errorf("session creation failed: %w", err)
}
defer session.Close()
if err := session.Run(command); err != nil {
return fmt.Errorf("command '%s' failed: %w", command, err)
}
return nil
}