-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (88 loc) · 1.8 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"golang.org/x/crypto/ssh"
)
func main() {
// Parsing Arguments
var (
port int
key string
pass string
)
flag.IntVar(&port, "port", 22, "Port to connect to on the remote host.")
flag.StringVar(&key, "i", "", "Selects a file from which the identity (private key) for public key authentication.")
flag.StringVar(&pass, "pass", "", "The password is given on the command line.")
flag.Parse()
user := flag.Arg(0)
host := flag.Arg(1)
file := flag.Arg(2)
auth := []ssh.AuthMethod{}
// Try Password Method
if pass != "" {
auth = append(auth, ssh.Password(pass))
}
// Try PrivateKey Method
if key != "" {
buf, err := ioutil.ReadFile(key)
if err != nil {
log.Println(err)
return
}
signer, err := ssh.ParsePrivateKey(buf)
if err != nil {
log.Println(err)
return
}
auth = append(auth, ssh.PublicKeys(signer))
}
config := &ssh.ClientConfig{
User: user,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Auth: auth,
}
// Try connecting to remote host
addr := fmt.Sprintf("%s:%d", host, port)
conn, err := ssh.Dial("tcp", addr, config)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
// Setup SSH Session
session, err := conn.NewSession()
if err != nil {
log.Println(err)
return
}
defer session.Close()
session.Stdout = os.Stdout
session.Stderr = os.Stderr
// Setup StdinPipe
stdin, err := session.StdinPipe()
if err != nil {
log.Println(err)
return
}
defer stdin.Close()
// Start a shell
if err := session.Shell(); err != nil {
log.Println(err)
return
}
// Open File
f, _ := os.Open(file)
buf := bytes.Buffer{}
buf.ReadFrom(f)
buf.WriteTo(stdin)
// Wait close ssion
if err := session.Wait(); err != nil {
log.Println(err)
return
}
}