/
util.go
124 lines (107 loc) · 2.49 KB
/
util.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
package cmd
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/manifoldco/promptui"
homedir "github.com/mitchellh/go-homedir"
"golang.org/x/crypto/ssh"
"golang.org/x/net/proxy"
)
type Host struct {
Host string
User string
Desc string
Timestamp int64
Owner string
Password string
Port int
Tor bool
}
var home, _ = homedir.Dir()
var HostsFile = filepath.Join(home, ".sshp_hosts.json")
func gethosts(path string) ([]Host, error) {
var hosts []Host
// Touch hosts file with empty array if it doesn't exist
_, err := os.Stat(HostsFile)
if os.IsNotExist(err) {
file, err := os.Create(HostsFile)
if err != nil {
log.Fatal(err)
}
output, err := json.Marshal(hosts)
if err != nil {
log.Fatal(err)
}
_, err = file.Write(output)
if err != nil {
log.Fatal(err)
}
file.Close()
}
// Read the hosts file
data, err := ioutil.ReadFile(HostsFile)
if err != nil && strings.HasSuffix(err.Error(), "such file or directory") {
return hosts, errors.New("No hosts configured")
}
err = json.Unmarshal(data, &hosts)
if err != nil {
fmt.Println("error:", err)
}
// Sort the hosts by their timestamp, most recent first
sort.Slice(hosts, func(i, j int) bool {
return hosts[i].Timestamp > hosts[j].Timestamp
})
return hosts, nil
}
func writehosts(hosts []Host) error {
output, err := json.Marshal(hosts)
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(HostsFile, output, 0644)
if err != nil {
log.Fatal(err)
}
return nil
}
func selecthost(hosts []Host) (int, error) {
templates := &promptui.SelectTemplates{
Label: "{{ .UserHost }}?",
Active: "> {{ .Desc | cyan }} ({{ .Owner }})",
Inactive: " {{ .Desc | cyan }} ({{ .Owner }})",
Selected: "> {{ .Desc | red | cyan }}",
}
prompt := promptui.Select{
Label: "Select host",
Items: hosts,
Templates: templates,
}
i, _, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return -1, err
}
return i, nil
}
func proxiedSSHClient(proxyAddress string, sshServerAddress string, sshConfig *ssh.ClientConfig) (*ssh.Client, error) {
dialer, err := proxy.SOCKS5("tcp", proxyAddress, nil, proxy.Direct)
if err != nil {
return nil, err
}
conn, err := dialer.Dial("tcp", sshServerAddress)
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, sshServerAddress, sshConfig)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}