-
Notifications
You must be signed in to change notification settings - Fork 0
/
04.4-04-sshclient-run-combinedoutput.go
executable file
·80 lines (66 loc) · 1.8 KB
/
04.4-04-sshclient-run-combinedoutput.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
// SSH login with user/pass. Run a command with CombinedOutput and print output.
package main
import (
"flag"
"fmt"
"net"
"os"
// Importing crypto/ssh
"golang.org/x/crypto/ssh"
)
var (
username, password, serverIP, serverPort, command string
)
// Read flags
func init() {
flag.StringVar(&serverPort, "port", "22", "SSH server port")
flag.StringVar(&serverIP, "ip", "127.0.0.1", "SSH server IP")
flag.StringVar(&username, "user", "", "username")
flag.StringVar(&password, "pass", "", "password")
flag.StringVar(&command, "cmd", "", "command to run")
}
func main() {
// Parse flags
flag.Parse()
// Check if username has been submitted - password can be empty
if username == "" {
fmt.Println("Must supply username")
os.Exit(2)
}
// Create SSH config
config := &ssh.ClientConfig{
// Username
User: username,
// Each config must have one AuthMethod. In this case we use password
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
// This callback function validates the server.
// Danger! We are ignoring host info
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// Server address
t := net.JoinHostPort(serverIP, serverPort)
// Connect to the SSH server
sshConn, err := ssh.Dial("tcp", t, config)
if err != nil {
fmt.Printf("Failed to connect to %v\n", t)
fmt.Println(err)
os.Exit(2)
}
// Create new SSH session
session, err := sshConn.NewSession()
if err != nil {
fmt.Printf("Cannot create SSH session to %v\n", t)
fmt.Println(err)
os.Exit(2)
}
// Close the session when main returns
defer session.Close()
// Run a command with CombinedOutput
o, err := session.CombinedOutput(command)
if err != nil {
fmt.Println("Error running command", err)
}
fmt.Printf("Output:\n%s", o)
}