forked from trzsz/trzsz-ssh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
224 lines (195 loc) · 5.6 KB
/
main.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/*
MIT License
Copyright (c) 2023 Lonny Wong <lonnywong@qq.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package tssh
import (
"fmt"
"os"
"strings"
"github.com/kevinburke/ssh_config"
"github.com/trzsz/go-arg"
"golang.org/x/term"
)
const kTsshVersion = "0.1.2"
type sshOption struct {
options map[string]string
}
type sshArgs struct {
Ver bool `arg:"-V,--" help:"show program's version number and exit"`
Destination string `arg:"positional" help:"alias in ~/.ssh/config, or [user@]hostname[:port]"`
Command string `arg:"positional" help:"command to execute instead of a login shell"`
Argument []string `arg:"positional" help:"command arguments separated by spaces"`
DisableTTY bool `arg:"-T,--" help:"disable pseudo-terminal allocation"`
ForceTTY bool `arg:"-t,--" help:"force pseudo-terminal allocation"`
Port int `arg:"-p,--" help:"port to connect to on the remote host"`
Identity string `arg:"-i,--" help:"identity (private key) for public key auth"`
ProxyJump string `arg:"-J,--" help:"jump hosts separated by comma characters"`
Option sshOption `arg:"-o,--" help:"options in the format used in ~/.ssh/config\ne.g., tssh -o ProxyCommand=\"ssh proxy nc %h %p\""`
DragFile bool `help:"enable drag files and directories to upload"`
TraceLog bool `help:"enable trzsz detect trace logs for debugging"`
Relay bool `help:"force trzsz run as a relay on the jump server"`
}
func (sshArgs) Description() string {
return "Simple ssh client with trzsz ( trz / tsz ) support.\n"
}
func (sshArgs) Version() string {
return fmt.Sprintf("trzsz ssh %s", kTsshVersion)
}
func (o *sshOption) UnmarshalText(b []byte) error {
s := string(b)
if s == fmt.Sprintf("%s", sshOption{}) {
return nil
}
pos := strings.Index(s, "=")
if pos < 1 {
return fmt.Errorf("invalid option: %s", s)
}
if o.options == nil {
o.options = make(map[string]string)
}
o.options[strings.ToLower(strings.TrimSpace(s[:pos]))] = strings.TrimSpace(s[pos+1:])
return nil
}
func (o *sshOption) get(option string) string {
if o.options == nil {
return ""
}
return o.options[strings.ToLower(option)]
}
func parseRemoteCommand(args *sshArgs) string {
if args.Command != "" {
if len(args.Argument) == 0 {
return args.Command
}
return fmt.Sprintf("%s %s", args.Command, strings.Join(args.Argument, " "))
}
return ssh_config.Get(args.Destination, "RemoteCommand")
}
var isTerminal bool = term.IsTerminal(int(os.Stdin.Fd()))
func parseCmdAndTTY(args *sshArgs) (cmd string, tty bool, err error) {
cmd = parseRemoteCommand(args)
if args.DisableTTY && args.ForceTTY {
err = fmt.Errorf("cannot specify -t with -T")
return
}
if args.DisableTTY {
tty = false
return
}
if args.ForceTTY {
tty = true
return
}
requestTTY := strings.ToLower(ssh_config.Get(args.Destination, "RequestTTY"))
switch requestTTY {
case "", "auto":
tty = isTerminal && (cmd == "")
case "no":
tty = false
case "force":
tty = true
case "yes":
tty = isTerminal
default:
err = fmt.Errorf("unknown RequestTTY option: %s", ssh_config.Get(args.Destination, "RequestTTY"))
}
return
}
func TsshMain() int {
var args sshArgs
parser := arg.MustParse(&args)
// compatible with -V option
if args.Ver {
fmt.Println(args.Version())
return 0
}
// print message after stdin reset
var err error
defer func() {
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
}()
// setup terminal
var mode *terminalMode
if isTerminal {
mode, err = setupTerminalMode()
if err != nil {
return 1
}
defer resetTerminalMode(mode)
}
// choose ssh alias
if args.Destination == "" {
if !isTerminal {
parser.WriteHelp(os.Stderr)
return 2
}
var quit bool
args.Destination, quit, err = chooseAlias()
if quit {
err = nil
return 0
}
if err != nil {
return 3
}
}
// parse cmd and tty
command, tty, err := parseCmdAndTTY(&args)
if err != nil {
return 4
}
// ssh login
client, session, err := sshLogin(&args, tty)
if err != nil {
return 5
}
defer client.Close()
defer session.Close()
// reset terminal if no tty
if !tty && mode != nil {
resetTerminalMode(mode)
}
// run command or start shell
if command != "" {
if !tty {
err = session.Run(command)
if err != nil {
return 6
}
return 0
}
if err = session.Start(command); err != nil {
err = fmt.Errorf("start command [%s] failed: %v", command, err)
return 7
}
} else {
if err = session.Shell(); err != nil {
err = fmt.Errorf("start shell failed: %v", err)
return 8
}
}
// wait for exit
if err = session.Wait(); err != nil {
err = nil // ignore wait error
return 9
}
return 0
}