diff --git a/commands/run_command.go b/commands/run_command.go index 9abc2d7..5e30aa3 100644 --- a/commands/run_command.go +++ b/commands/run_command.go @@ -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"` diff --git a/commands/utils.go b/commands/utils.go new file mode 100644 index 0000000..4bf3a63 --- /dev/null +++ b/commands/utils.go @@ -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 +} +