You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.2 KiB
Go

package commands
import (
"fmt"
"os"
"golang.org/x/crypto/ssh"
)
func ResolvePort(host string) string {
if len(host) > 0 {
hasPort := false
for i := len(host) - 1; i >= 0; i-- {
if host[i] == ':' {
hasPort = true
break
}
if host[i] == ']' {
break
}
}
if !hasPort {
host = host + ":22"
}
}
return host
}
func GetSigner(private_key_file string) (ssh.Signer, error) {
key_bytes, err := os.ReadFile(private_key_file)
if err != nil {
return nil, fmt.Errorf("error reading private key from file %s: %w", private_key_file, err)
}
signer, err := ssh.ParsePrivateKey(key_bytes)
if err != nil {
return nil, fmt.Errorf("error parsing private key: %w", err)
}
return signer, nil
}
func GetClient(private_key_file, username, host string) (*ssh.Client, error) {
signer, err := GetSigner(private_key_file)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
addr := ResolvePort(host)
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
return nil, fmt.Errorf("error connecting to server: %w", err)
}
return client, nil
}