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.
55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package commands
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
type RunCommandArgs struct {
|
|
Command string `json:"command"`
|
|
RemoteCommand string `json:"remote_command"`
|
|
PrivateKeyFile string `json:"private_key_file"`
|
|
Username string `json:"username"`
|
|
Host string `json:"host"`
|
|
Sudo bool `json:"sudo"`
|
|
}
|
|
|
|
func (rca *RunCommandArgs) ReadArgs() {
|
|
|
|
if len(os.Args) != 6 {
|
|
fmt.Fprintf(os.Stderr, "Usage: %s run_command <remote-command> <private-key> <username> <host>\n", os.Args[0])
|
|
os.Exit(1)
|
|
}
|
|
|
|
rca.Command = os.Args[1]
|
|
rca.RemoteCommand = os.Args[2]
|
|
rca.PrivateKeyFile = os.Args[3]
|
|
rca.Username = os.Args[4]
|
|
rca.Host = os.Args[5]
|
|
|
|
}
|
|
|
|
func RunCommand(args RunCommandArgs, stdout, stderr io.Writer) error {
|
|
|
|
client, err := GetClient(args.PrivateKeyFile, args.Username, args.Host)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer client.Close()
|
|
|
|
session, err := client.NewSession()
|
|
if err != nil {
|
|
return fmt.Errorf("error creating SSH session: %w", err)
|
|
}
|
|
defer session.Close()
|
|
|
|
session.Stdout = stdout
|
|
session.Stderr = stderr
|
|
if err := session.Run(args.RemoteCommand); err != nil {
|
|
return fmt.Errorf("error running command: %w", err)
|
|
}
|
|
return nil
|
|
|
|
}
|