-
Notifications
You must be signed in to change notification settings - Fork 0
/
remoteSsh.go
70 lines (67 loc) · 2.06 KB
/
remoteSsh.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
package utils
import (
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"io/ioutil"
"time"
)
func RemoteCmd(IP, Port, User, CMD, idRsaPath string) (string, error) {
// ======================================= ssh ===========================
user := User
address := IP
command := CMD
port := Port
key, err := ioutil.ReadFile(idRsaPath)
if err != nil {
logrus.Errorf("[util - remote-ssh] | ❌ false|unable to read private key: %v", err)
return "null", err
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
//logrus.Info(key)
if err != nil {
logrus.Errorf("[util - remote-ssh] | ❌ false|unable to parse private key: %v", err)
}
//hostKeyCallback, err := kh.New("./data/known_hosts")
if err != nil {
logrus.Errorf("[util - remote-ssh] | ❌ false|could not create hostkeycallback function: %v ", err)
return "null", err
}
config := &ssh.ClientConfig{
User: user,
Timeout: time.Second * 2, //2s 超时
Auth: []ssh.AuthMethod{
// Add in password check here for moar security.
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
//HostKeyCallback: ssh.InsecureIgnoreHostKey(),
//HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
// return nil
//},
}
// Connect to the remote server and perform the SSH handshake.
client, err := ssh.Dial("tcp", address+":"+port, config)
if err != nil {
logrus.Errorf("[util - remote-ssh] | ❌ false|unable to connect: %v", err)
return "null", err
}
defer client.Close()
ss, err := client.NewSession()
if err != nil {
logrus.Errorf("[util - remote-ssh] | ❌ false|unable to create SSH session: %v", err)
return "null", err
}
defer ss.Close()
// Creating the buffer which will hold the remotly executed command's output.
//var stdoutBuf bytes.Buffer
//ss.Stdout = &stdoutBuf
//err = ss.Run(command)
//执行远程命令
combo, err := ss.CombinedOutput(command)
if err != nil {
logrus.Errorf("[util - remote-ssh] | ❌ false| Err ===》%v", err)
return "null", err
}
return string(combo), nil
}