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.

73 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 {
key_bytes, err := os.ReadFile(private_key_file)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading private key from file %s: %v\n", private_key_file, err)
os.Exit(1)
}
signer, err := ssh.ParsePrivateKey(key_bytes)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing private key: %v\n", err)
os.Exit(1)
}
return signer
}
func GetClient(private_key_file, username, host string) *ssh.Client {
signer := GetSigner(private_key_file)
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 {
fmt.Fprintf(os.Stderr, "Error connecting to server: %v\n", err)
os.Exit(1)
}
return client
}