move command package utilities into separate file

master
Joshua Herring 1 month ago
parent c55bcf60c3
commit f5cebdff81

@ -3,73 +3,8 @@ 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
}
type RunCommandArgs struct {
Command string `json:"command"`
RemoteCommand string `json:"remote_command"`

@ -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…
Cancel
Save