Files
go-ssh-app/ssh/connect.go
2024-12-28 15:54:49 +01:00

50 lines
1.1 KiB
Go

package ssh
import (
"fmt"
"io/ioutil"
"golang.org/x/crypto/ssh"
)
type SSHConfig struct {
User string
Host string
Port string
Password string
PrivateKey string
}
func ConnectSSH(config SSHConfig) error {
var auth ssh.AuthMethod
if config.PrivateKey != "" {
key, err := ioutil.ReadFile(config.PrivateKey)
if err != nil {
return fmt.Errorf("failed to read private key: %v", err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return fmt.Errorf("failed to parse private key: %v", err)
}
auth = ssh.PublicKeys(signer)
} else {
auth = ssh.Password(config.Password)
}
clientConfig := &ssh.ClientConfig{
User: config.User,
Auth: []ssh.AuthMethod{auth},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // Use a proper callback for production!
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", config.Host, config.Port), clientConfig)
if err != nil {
return fmt.Errorf("failed to connect to SSH: %v", err)
}
defer client.Close()
fmt.Println("Connected to SSH successfully!")
return nil
}