-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshutil.go
114 lines (97 loc) · 2.11 KB
/
sshutil.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
package sshutil
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"net"
"os"
"time"
"golang.org/x/crypto/ssh"
)
const (
bitSize = 2048
port = "22"
)
type SSHClient struct {
conn *ssh.Client
config *ssh.ClientConfig
}
func NewClient(host string, user string, privKeyFile string) (*SSHClient, error) {
cfg := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
publicKeyFile(privKeyFile),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", host, port), cfg)
if err != nil {
return nil, err
}
return &SSHClient{
conn: conn,
config: cfg,
}, nil
}
func (c *SSHClient) RunAsSudo(command string) error {
session, err := c.conn.NewSession()
if err != nil {
return err
}
defer session.Close()
return session.Run(fmt.Sprintf("sudo %s", command))
}
func (c *SSHClient) RunAsUser(command string) error {
session, err := c.conn.NewSession()
if err != nil {
return err
}
defer session.Close()
return session.Run(fmt.Sprintf(command))
}
func publicKeyFile(file string) ssh.AuthMethod {
buffer, err := os.ReadFile(file)
if err != nil {
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil
}
return ssh.PublicKeys(key)
}
// Generate public and private rsa keys
func GenerateNewSSHKeys() ([]byte, []byte, error) {
// Generate private key
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, nil, err
}
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyPEM := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyBytes,
},
)
// Generate public key
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, nil, err
}
publicKeyBytes := ssh.MarshalAuthorizedKey(pub)
return privateKeyPEM, publicKeyBytes, nil
}
// Check if host is responding
func IsResponding(ip string) bool {
timeout := time.Second
conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), timeout)
if err != nil {
return false
}
defer conn.Close()
return conn != nil
}