-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsshclient-run.go
More file actions
87 lines (71 loc) · 1.89 KB
/
sshclient-run.go
File metadata and controls
87 lines (71 loc) · 1.89 KB
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
// SSH login with user/pass. Run a command with Run and print output.
package main
import (
"bytes"
"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()
// Create buffers for stdout and stderr
var o, e bytes.Buffer
session.Stdout = &o
session.Stderr = &e
// Run a command with Run and read stdout and stderr
if err := session.Run(command); err != nil {
fmt.Println("Error running command", err)
}
// Convert buffer to string
fmt.Printf("stdout:\n%s\nstderr:\n%s", o.String(), e.String())
}