-
Notifications
You must be signed in to change notification settings - Fork 1
/
sshdiff.go
executable file
·110 lines (93 loc) · 2.1 KB
/
sshdiff.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
package main
import (
"fmt"
"bufio"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
var TEMP_DIR string = filepath.Join(os.TempDir(), "sshdiff")
func check_args() {
if len(os.Args) != 3+1 {
fmt.Println(`Usage:
sshdiff HOSTNAME_1 HOSTNAME_2 COMMAND
`)
os.Exit(1)
}
}
func dir_exist(dir string) bool {
_, err := os.Stat(TEMP_DIR)
if err != nil {
return false
} else {
return true
}
}
func mktempdir() {
if !dir_exist(TEMP_DIR) {
if err := os.Mkdir(TEMP_DIR, 0777); err != nil {
panic(err)
}
}
}
func diff(a string, b string, hostname_1 string, hostname_2 string) string {
mktempdir()
t := time.Now()
var (
tempfile_1 string = filepath.Join(TEMP_DIR, hostname_1+t.Format("20060102150405"))
tempfile_2 string = filepath.Join(TEMP_DIR, hostname_2+t.Format("20060102150405"))
)
err := ioutil.WriteFile(tempfile_1, []byte(a), 0644)
if err != nil {
panic(err)
}
err = ioutil.WriteFile(tempfile_2, []byte(b), 0644)
if err != nil {
panic(err)
}
stdout, _ := exec.Command("diff", "-u", tempfile_1, tempfile_2).Output()
return string(stdout)
}
func run_ssh_command(host string, command string) string {
fmt.Println("Running command in " + host + "..." + command)
// Prepare
cmd := exec.Command("ssh", host, command) // ToDo Appendable -v option
cmd.Stdin = strings.NewReader("PASSWORD" + "\n")
cmd.Stderr = os.Stderr
stdout, _ := cmd.StdoutPipe()
scanner := bufio.NewScanner(stdout)
scanner.Split(bufio.ScanBytes)
// Run
if err := cmd.Start(); err != nil {
fmt.Println(err)
}
// Collect stdout
var stdout_byte string
for scanner.Scan() {
stdout_byte += scanner.Text()
}
// Clean
defer stdout.Close()
cmd.Wait()
return string(stdout_byte)
}
func main() {
check_args()
var (
hostname_1 string = os.Args[1]
hostname_2 string = os.Args[2]
command string = os.Args[3]
)
result1 := run_ssh_command(hostname_1, command)
result2 := run_ssh_command(hostname_2, command)
if result1 != result2 {
fmt.Println(diff(result1, result2, hostname_1, hostname_2))
os.Exit(-1)
} else {
fmt.Println("No difference. All results same")
os.Exit(0)
}
}