-
-
Notifications
You must be signed in to change notification settings - Fork 457
/
Copy pathssh-client.go
132 lines (108 loc) · 2.49 KB
/
ssh-client.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"golang.org/x/crypto/ssh"
)
var (
user string
host string
port string
keyfile string
)
func init() {
flag.StringVar(&user, "u", "root", "SSH user")
flag.StringVar(&host, "h", "example.tld", "Host")
flag.StringVar(&port, "p", "22", "SSH port")
flag.StringVar(&keyfile, "pk", "", "Public key file, e.g.: \"~/.ssh/id_rsa\"")
}
func main() {
flag.Parse()
if host == "example.tld" {
fmt.Println("Usage: go run ssh-client.go -h <host> -p <port> -pk <path_to_private_key>")
flag.PrintDefaults()
return
}
var client *ssh.Client
var err error
if keyfile != "" {
client, err = connectToHostWithPublicKey(user, fmt.Sprintf("%v:%v", host, port), keyfile)
} else {
client, err = connectToHost(user, fmt.Sprintf("%v:%v", host, port))
}
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to connect: %v\n", err)
return
}
defer client.Close()
runRemoteCommands(client)
}
func connectToHost(user, host string) (*ssh.Client, error) {
var password string
fmt.Print("SSH Password: ")
fmt.Scanf("%s\n", &password)
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host, sshConfig)
if err != nil {
return nil, err
}
return client, nil
}
func connectToHostWithPublicKey(user, host, publicKeyFile string) (*ssh.Client, error) {
key, err := ioutil.ReadFile(publicKeyFile)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, err
}
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host, sshConfig)
if err != nil {
return nil, err
}
return client, nil
}
func runRemoteCommands(client *ssh.Client) {
commands := []string{
"ls -al",
"df -h",
"uptime",
"whoami",
}
for _, cmd := range commands {
output, err := executeRemoteCommand(client, cmd)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to run command '%s': %v\n", cmd, err)
continue
}
fmt.Printf("Output of '%s':\n%s\n", cmd, output)
}
}
func executeRemoteCommand(client *ssh.Client, command string) (string, error) {
session, err := client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
output, err := session.CombinedOutput(command)
if err != nil {
return "", err
}
return string(output), nil
}