-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathssh.go
142 lines (105 loc) · 2.41 KB
/
ssh.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package main
// https://github.com/kirinlabs/HttpRequest
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"time"
"golang.org/x/crypto/ssh"
)
func PublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
fmt.Println(err)
return nil
}
return ssh.PublicKeys(key)
}
func exec_command(params CloudShellEnv) {
file, err := env_get_ssh_pkey()
if err != nil {
fmt.Println("\nTip: Run the command: \"gcloud alpha cloud-shell ssh --dry-run\" to setup Cloud Shell SSH keys")
return
}
sshConfig := &ssh.ClientConfig{
User: params.SshUsername,
Auth: []ssh.AuthMethod{
PublicKeyFile(file),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
sshHost := params.SshHost
sshPort := fmt.Sprint(params.SshPort)
host := sshHost + ":" + sshPort
// fmt.Println("Dial")
// fmt.Println(host)
connection, err := ssh.Dial("tcp", host, sshConfig)
if err != nil {
// return nil, fmt.Errorf("Failed to dial: %s", err)
fmt.Println(err)
return
}
defer connection.Close()
if config.Debug == true {
fmt.Println("Connect")
}
session, err := connection.NewSession()
if err != nil {
// return nil, fmt.Errorf("Failed to create session: %s", err)
fmt.Println(err)
return
}
defer session.Close()
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Stderr = &stderrBuf
if config.Debug == true {
fmt.Println("Run Command:", config.RemoteCommand)
}
session.Run(config.RemoteCommand)
fmt.Printf("%s\n", stdoutBuf.String())
fmt.Printf("%s\n", stderrBuf.String())
}
func exec_ssh(params CloudShellEnv) {
key, err := env_get_ssh_pkey()
if err != nil {
return
}
sshUsername := params.SshUsername
sshHost := params.SshHost
sshPort := fmt.Sprint(params.SshPort)
sshUrl := sshUsername + "@" + sshHost
if config.Debug == true {
fmt.Println(key)
fmt.Println(sshUsername)
fmt.Println(sshHost)
fmt.Println(sshPort)
fmt.Println(sshUrl)
}
for x:= 0; x < 3; x++ {
if x > 0 {
fmt.Println("Retrying ...")
time.Sleep(1000 * time.Millisecond)
}
cmd := exec.Command("ssh", "-p", sshPort, "-i", key, sshUrl)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err == nil {
return
}
}
fmt.Println(err)
}