move command package utilities into separate file
parent
c55bcf60c3
commit
f5cebdff81
@ -0,0 +1,72 @@
|
|||||||
|
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: %v\n", 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
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in New Issue