/
cscp.go
90 lines (78 loc) · 2.03 KB
/
cscp.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
89
90
// This file is part of cssh.
//
// Copyright (C) 2016-2018 David Gamba Rios
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
/*
Package main provides a way to scp using credentials stored in your ~/.ssh/config file.
*/
package main
import (
"fmt"
"os"
"time"
"github.com/DavidGamba/cssh/common"
"github.com/DavidGamba/gexpect"
// "github.com/shavac/gexpect"
"github.com/DavidGamba/go-getoptions"
)
func synopsis() {
synopsis := `cscp [--timeout <seconds>] [--key [<key-index>]] [--debug] [SCP ARGS and Options...]
cscp -h # show this help`
fmt.Fprintln(os.Stderr, synopsis)
}
func main() {
var timeoutSeconds int
var keyIndex int
opt := getoptions.New()
opt.SetUnknownMode(getoptions.Pass)
opt.Bool("help", false)
opt.IntVarOptional(&keyIndex, "key", -1)
opt.BoolVar(&common.DebugFlag, "debug", false)
opt.IntVar(&timeoutSeconds, "timeout", 5)
remaining, err := opt.Parse(os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
if opt.Called("help") {
synopsis()
os.Exit(1)
}
if len(remaining) < 1 {
fmt.Fprintf(os.Stderr, "Missing hostname")
os.Exit(1)
}
passwords := common.ReadConfig(remaining[0])
common.Debug(passwords)
command := []string{}
if opt.Called("key") {
keys := common.GetKeyList()
if keyIndex == -1 {
for i, v := range keys {
fmt.Fprintf(os.Stderr, "%d: %s\n", i, v)
}
os.Exit(1)
}
command = append(command, "-i")
command = append(command, keys[keyIndex])
}
command = append(command, remaining...)
child, _ := gexpect.NewSubProcess("scp", command...)
common.Debug("scp", command)
if err := child.Start(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
defer child.Close()
// if debugFlag {
// child.Echo()
// }
err = common.SSHLogin(child, time.Duration(timeoutSeconds)*time.Second, passwords)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
child.InteractTimeout(0)
}