-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
103 lines (91 loc) · 2.31 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
// link: http://blog.ralch.com/tutorial/golang-ssh-connection/
import (
"fmt"
"golang.org/x/crypto/ssh"
"net"
"io/ioutil"
"log"
"time"
)
const (
CERT_PASSWORD = 1
CERT_PUBLIC_KEY_FILE = 2
DEFAULT_TIMEOUT = 3 // second
)
type SSH struct{
Ip string
User string
Cert string //password or key file path
Port int
session *ssh.Session
client *ssh.Client
}
func (ssh_client *SSH) 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 *SSH) Connect(mode int) {
var ssh_config *ssh.ClientConfig
var auth []ssh.AuthMethod
if mode == CERT_PASSWORD {
auth = []ssh.AuthMethod{ssh.Password(ssh_client.Cert)}
} else if mode == CERT_PUBLIC_KEY_FILE {
auth = []ssh.AuthMethod{ssh_client.readPublicKeyFile(ssh_client.Cert)}
} else {
log.Println("does not support mode: ", mode)
return
}
ssh_config = &ssh.ClientConfig{
User: ssh_client.User,
Auth: auth,
//需要验证服务端,不做验证返回nil就可以,点击HostKeyCallback看源码就知道了
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout:time.Second * DEFAULT_TIMEOUT,
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", ssh_client.Ip, ssh_client.Port), ssh_config)
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 *SSH) RunCmd(cmd string) {
out, err := ssh_client.session.CombinedOutput(cmd)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}
func (ssh_client *SSH) Close() {
ssh_client.session.Close()
ssh_client.client.Close()
}
//demo
func main() {
client := &SSH{
Ip: "your ip",
User : "root",
Port:22,
Cert:"your password",
}
client.Connect(CERT_PASSWORD)
client.RunCmd("ls /home")
client.Close()
}