-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsshClient.go
More file actions
85 lines (69 loc) · 1.62 KB
/
sshClient.go
File metadata and controls
85 lines (69 loc) · 1.62 KB
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
package main
// From https://github.com/jilieryuyi/ssh-simple-client/blob/master/main.go
// link: http://blog.ralch.com/tutorial/golang-ssh-connection/
import (
"fmt"
"io/ioutil"
"net"
"time"
"golang.org/x/crypto/ssh"
)
const defaultTimeout = 3 // second
type sshClient struct {
IP string
User string
Cert string //password or key file path
Port int
session *ssh.Session
client *ssh.Client
}
func (ssh_client *sshClient) readPublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil
}
return ssh.PublicKeys(key)
}
func (ssh_client *sshClient) Connect() {
var sshConfig *ssh.ClientConfig
var auth []ssh.AuthMethod
auth = []ssh.AuthMethod{ssh_client.readPublicKeyFile(ssh_client.Cert)}
sshConfig = &ssh.ClientConfig{
User: ssh_client.User,
Auth: auth,
// HostKeyCallback
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: time.Second * defaultTimeout,
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", ssh_client.IP, ssh_client.Port), sshConfig)
if err != nil {
fmt.Println(err)
return
}
session, err := client.NewSession()
if err != nil {
fmt.Println(err)
client.Close()
return
}
ssh_client.session = session
ssh_client.client = client
}
func (ssh_client *sshClient) RunCmd(cmd string) []byte {
out, err := ssh_client.session.Output(cmd)
if err != nil {
fmt.Println(err)
}
return out
}
func (ssh_client *sshClient) Close() {
ssh_client.session.Close()
ssh_client.client.Close()
}
//demo