-
Notifications
You must be signed in to change notification settings - Fork 15
/
scp.go
88 lines (74 loc) · 1.68 KB
/
scp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package cmd
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"github.com/cybozu-go/well"
"github.com/spf13/cobra"
)
func detectSCPNode(args []string) (string, error) {
var nodeName string
for _, arg := range args {
if strings.Contains(arg, ":") {
nodeName = detectSSHNode(arg[:strings.Index(arg, ":")])
break
}
}
if len(nodeName) == 0 {
return "", errors.New("node name is not specified")
}
return nodeName, nil
}
func scp(ctx context.Context, args []string) error {
node, err := detectSCPNode(args)
if err != nil {
return err
}
fifo, err := sshPrivateKey(node)
if err != nil {
return err
}
defer os.Remove(fifo)
scpArgs := []string{
"-i", fifo,
"-o", "UserKnownHostsFile=/dev/null",
"-o", "StrictHostKeyChecking=no",
"-o", "ConnectTimeout=60",
}
if scpParams.recursive {
scpArgs = append(scpArgs, "-r")
}
scpArgs = append(scpArgs, args...)
fmt.Println(scpArgs)
c := exec.CommandContext(ctx, "scp", scpArgs...)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return c.Run()
}
var scpParams struct {
recursive bool
}
// scpCmd represents the scp command
var scpCmd = &cobra.Command{
Use: "scp [[user@]NODE1:]FILE1 ... [[user@]NODE2:]FILE2",
Short: "copy files between hosts via scp",
Long: `Copy files between hosts via scp.
NODE is IP address or hostname of the node.
`,
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
well.Go(func(ctx context.Context) error {
return scp(ctx, args)
})
well.Stop()
return well.Wait()
},
}
func init() {
scpCmd.Flags().BoolVarP(&scpParams.recursive, "", "r", false, "recursively copy entire directories")
rootCmd.AddCommand(scpCmd)
}