From 3951855adfb473ae696d936c7ebee3840d346627 Mon Sep 17 00:00:00 2001 From: Jan Dubois Date: Thu, 29 Apr 2021 17:07:17 -0700 Subject: [PATCH] Add cp command to transfer file in and out of a machine Uses scp syntax; a ':' prefix will be replaced by 'user@host:'. Signed-off-by: Jan Dubois --- cmd/cp.go | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 cmd/cp.go diff --git a/cmd/cp.go b/cmd/cp.go new file mode 100644 index 0000000..6377fe7 --- /dev/null +++ b/cmd/cp.go @@ -0,0 +1,77 @@ +package cmd + +import ( + "fmt" + "os" + "os/exec" + "strconv" + "strings" + + "github.com/docker/machine/libmachine/state" + "github.com/spf13/cobra" +) + +func init() { + rootCmd.AddCommand(cpCmd) +} + +var cpCmd = &cobra.Command{ + Use: "cp [SOURCE] [DEST]", + Short: "Copy files into or out of a machine.", + Long: `Copy files into or out of a machine.`, + Args: cobra.ExactArgs(2), + RunE: cpCommand, +} + +func cpCommand(cmd *cobra.Command, args []string) error { + api := newAPI() + defer api.Close() + + host, err := api.Load(machineName) + if err != nil { + return err + } + + currentState, err := host.Driver.GetState() + if err != nil { + return err + } + + if currentState != state.Running { + return fmt.Errorf("cannot run cp command: Host %q is not running", host.Name) + } + + port, err := host.Driver.GetSSHPort() + if err != nil { + return err + } + + scpArgs := []string{ + "-P", strconv.Itoa(port), + "-i", host.Driver.GetSSHKeyPath(), + "-o", "IdentitiesOnly=yes", + "-o", "LogLevel=quiet", + "-o", "PasswordAuthentication=no", + "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + } + + sshUserame := host.Driver.GetSSHUsername() + sshHostname, err := host.Driver.GetSSHHostname() + if err != nil { + return err + } + + for _, arg := range args { + if strings.HasPrefix(arg, ":") { + scpArgs = append(scpArgs, fmt.Sprintf("%s@%s%s", sshUserame, sshHostname, arg)) + } else { + scpArgs = append(scpArgs, arg) + } + } + + command := exec.Command("scp", scpArgs...) + command.Stdout = os.Stdout + command.Stderr = os.Stderr + return command.Run() +}