-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinux.go
More file actions
483 lines (469 loc) · 11.8 KB
/
linux.go
File metadata and controls
483 lines (469 loc) · 11.8 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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package linux
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/gospider007/re"
"github.com/gospider007/tools"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type ClientOption struct {
Timeout time.Duration //连接超时时间
Host string //远程host
Port int //远程port
Usr string //用户名
Pwd string //密码
KeyPath string //key文件的路径,当使用key登陆时使用
KeyData []byte //key文件的内容,当使用key登陆时使用
}
type Client struct {
client *ssh.Client
pwd string
usr string
}
type Ssh struct {
client *ssh.Session
}
type Sftp struct {
client *sftp.Client
}
type Screen struct {
IsRun bool
client *Ssh
pip *ScreenPip
waitTime time.Duration
usr string
pwd string
suffix string
ctx context.Context
cnl context.CancelFunc
}
type ScreenPip struct {
inData chan []byte
outData chan []byte
waitTime time.Duration
ctx context.Context
cnl context.CancelFunc
}
func (obj *ScreenPip) Read(con []byte) (int, error) {
select {
case ron := <-obj.inData:
return copy(con, ron), nil
case <-obj.ctx.Done():
return 0, io.EOF
}
}
func (obj *ScreenPip) Write(con []byte) (int, error) {
afterTime := time.NewTimer(obj.waitTime)
defer afterTime.Stop()
select {
case obj.outData <- con:
return len(con), nil
case <-obj.ctx.Done():
return 0, io.EOF
case <-afterTime.C:
return 0, io.EOF
}
}
func (obj *ScreenPip) Close() error {
obj.cnl()
return nil
}
type TermOption struct {
Type string //defalut xterm
DisEcho bool // 是否禁用回显
InSpeed uint32 // input speed = 14.4kbaud
OutSpeed uint32 //output speed = 14.4kbaud
Row int
Col int
}
func NewClient(option ClientOption) (*Client, error) {
config := &ssh.ClientConfig{
User: option.Usr,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
if option.Timeout == 0 {
option.Timeout = time.Second * 30
}
config.Timeout = option.Timeout
if option.Pwd != "" {
config.Auth = []ssh.AuthMethod{ssh.Password(option.Pwd)}
} else if option.KeyData != nil {
signer, err := ssh.ParsePrivateKey(option.KeyData)
if err != nil {
return nil, err
}
config.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
} else if option.KeyPath != "" {
if tools.PathExist(option.KeyPath) {
key, err := os.ReadFile(option.KeyPath)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, err
}
config.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
} else {
return nil, errors.New("key path is not found")
}
} else {
return nil, errors.New("请输入密码")
}
addr := net.JoinHostPort(option.Host, strconv.Itoa(option.Port))
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
return nil, err
}
return &Client{client: client, pwd: option.Pwd, usr: option.Usr}, nil
}
func (obj *Client) Close() error {
return obj.client.Close()
}
func (obj *Client) NewSftp() (*Sftp, error) {
session, err := sftp.NewClient(obj.client)
if err != nil {
return nil, err
}
return &Sftp{client: session}, err
}
func (obj *Client) NewSsh() (*Ssh, error) {
client, err := obj.client.NewSession()
if err != nil {
return nil, err
}
return &Ssh{client: client}, err
}
func (obj *Client) NewScreen(preCtx context.Context, name string, waitTimes ...time.Duration) (*Screen, error) {
if preCtx == nil {
preCtx = context.TODO()
}
client, err := obj.NewSsh()
if err != nil {
return nil, err
}
var waitTime time.Duration
if len(waitTimes) > 0 {
waitTime = waitTimes[0]
} else {
waitTime = time.Second * 5
}
ctx, cnl := context.WithCancel(preCtx)
pip := ScreenPip{inData: make(chan []byte), outData: make(chan []byte), waitTime: waitTime, ctx: ctx, cnl: cnl}
client.SetStdIn(&pip)
client.SetStdOut(&pip)
client.SetStdErr(&pip)
if err := client.Term(); err != nil {
cnl()
client.Close()
return nil, err
}
screen := &Screen{
client: client,
pip: &pip,
waitTime: waitTime,
usr: obj.usr,
pwd: obj.pwd,
ctx: ctx,
cnl: cnl,
}
if !screen.initSuffix(screen.bytes()) {
return nil, errors.New("打开 linux 失败")
}
cmd := []byte(fmt.Sprintf("screen -x %s\n", name))
runCon, err := screen.Run(cmd)
if err != nil {
screen.Close()
return nil, err
}
screenCon := tools.BytesToString(runCon)
if strings.Contains(screenCon, "here is no screen to be attached matching") {
screen.Close()
return nil, errors.New("screen不存在")
}
return screen, nil
}
func (obj *Screen) initSuffix(txt []byte) bool { //获取前缀 Suffix
sss := bytes.Split(txt, []byte("\n"))
lastBytes := tools.BytesToString(sss[len(sss)-1])
rs := re.Search(fmt.Sprintf(`%s@[\w-]+`, obj.usr), lastBytes)
if rs == nil {
return false
}
obj.suffix = rs.Group()
return true
}
func (obj *Screen) hasSuffix(txt []byte) bool { //获取前缀 Suffix
sss := bytes.Split(txt, []byte("\n"))
st := sss[len(sss)-1]
return strings.Contains(tools.BytesToString(st), obj.suffix)
}
func (obj *Screen) bytes() []byte {
var allCon []byte
lastTime := time.Now().Add(obj.waitTime)
var afterTime *time.Timer
defer func() {
if afterTime != nil {
afterTime.Stop()
}
}()
for {
if afterTime == nil {
afterTime = time.NewTimer(obj.waitTime)
} else {
afterTime.Reset(obj.waitTime)
}
select {
case con := <-obj.pip.outData:
allCon = append(allCon, con...)
if time.Since(lastTime) > 0 {
obj.IsRun = true
return allCon
}
case <-afterTime.C:
obj.IsRun = !obj.hasSuffix(allCon)
return allCon
}
}
}
func (obj *Screen) Run(cmd []byte) ([]byte, error) {
afterTime := time.NewTimer(obj.waitTime)
defer afterTime.Stop()
select {
case obj.pip.inData <- cmd:
return obj.bytes(), nil
case <-afterTime.C:
return nil, errors.New("timeOut")
}
}
func (obj *Screen) SudoRun(cmd []byte) ([]byte, error) {
allCon, err := obj.Run(cmd)
if err != nil {
return allCon, err
}
if obj.pwd != "" {
rs := re.Search(`\n\[sudo\].*?[::]\s*?$`, string(allCon))
if rs != nil {
runCon, err := obj.Run([]byte(fmt.Sprintf("%s\n", obj.pwd)))
if err != nil {
return allCon, err
}
allCon = append(allCon, runCon...)
}
}
return allCon, nil
}
func (obj *Screen) Close() error {
obj.cnl()
return obj.client.Close()
}
func (obj *Ssh) Output(cmd string) ([]byte, error) {
return obj.client.Output(cmd)
}
func (obj *Ssh) CombinedOutput(cmd string) ([]byte, error) {
return obj.client.CombinedOutput(cmd)
}
func (obj *Ssh) Term(options ...TermOption) error {
var option TermOption
if len(options) > 0 {
option = options[0]
}
if option.InSpeed == 0 {
option.InSpeed = 14400
}
if option.OutSpeed == 0 {
option.OutSpeed = 14400
}
if option.Type == "" {
option.Type = "xterm-256color"
}
var echo uint32
if !option.DisEcho {
echo = 1
}
if obj.client.Stdin == nil {
obj.SetStdIn(os.Stdin)
}
if obj.client.Stdout == nil {
obj.SetStdOut(os.Stdout)
}
if obj.client.Stderr == nil {
obj.SetStdErr(os.Stderr)
}
modes := ssh.TerminalModes{
ssh.ECHO: echo, // 禁用回显(0禁用,1启动)
ssh.TTY_OP_ISPEED: option.InSpeed, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: option.OutSpeed, //output speed = 14.4kbaud
}
if err := obj.client.RequestPty(option.Type, option.Row, option.Col, modes); err != nil {
return err
}
return obj.client.Shell()
}
func (obj *Ssh) SetStdIn(val io.Reader) {
obj.client.Stdin = val
}
func (obj *Ssh) SetStdOut(val io.Writer) {
obj.client.Stdout = val
}
func (obj *Ssh) SetStdErr(val io.Writer) {
obj.client.Stderr = val
}
func (obj *Ssh) StdErrPipe() (io.Reader, error) {
return obj.client.StderrPipe()
}
func (obj *Ssh) StdInPipe() (io.WriteCloser, error) {
return obj.client.StdinPipe()
}
func (obj *Ssh) StdOutPipe() (io.Reader, error) {
return obj.client.StdoutPipe()
}
func (obj *Ssh) Close() error {
return obj.client.Close()
}
func (obj *Sftp) Upload(local_path string, remote_paths ...string) error {
if !tools.PathExist(local_path) {
return errors.New("local path not found")
}
local_path_info, err := os.Stat(local_path)
if err != nil {
return err
}
var remote_path string
if len(remote_paths) == 0 {
remote_path, err = obj.client.Getwd()
if err != nil {
return err
}
} else {
remote_path = remote_paths[0]
remote_path_info, err := obj.client.Stat(remote_path)
if err != nil {
return err
}
if !remote_path_info.IsDir() {
return errors.New("remote not is dir")
}
}
if local_path_info.IsDir() {
return obj.UploadDir(local_path, obj.client.Join(remote_path, local_path_info.Name()))
}
return obj.UploadFile(local_path, obj.client.Join(remote_path, local_path_info.Name()))
}
func (obj *Sftp) UploadFile(local_path string, remote_path string) error {
dstFile, err := obj.client.Create(remote_path)
if err != nil {
return err
}
defer dstFile.Close()
local_content, err := os.ReadFile(local_path)
if err != nil {
return err
}
dstFile.Write(local_content)
return nil
}
func (obj *Sftp) UploadDir(local_path string, remote_path string) error {
err := obj.client.Mkdir(remote_path)
if err != nil {
return err
}
localFiles, err := os.ReadDir(local_path)
if err != nil {
return err
}
for _, localFile := range localFiles {
if localFile.IsDir() {
err := obj.UploadDir(path.Join(local_path, localFile.Name()), obj.client.Join(remote_path, localFile.Name()))
if err != nil {
return err
}
} else {
err := obj.UploadFile(path.Join(local_path, localFile.Name()), obj.client.Join(remote_path, localFile.Name()))
if err != nil {
return err
}
}
}
return nil
}
func (obj *Sftp) Download(remote_path string, local_paths ...string) error {
remote_path_info, err := obj.client.Stat(remote_path)
if err != nil {
return err
}
var local_path string
if len(local_paths) == 0 {
_, dir, _, ok := runtime.Caller(1)
if !ok {
return errors.New("获取当前目录错误")
}
local_path = filepath.Dir(dir)
} else {
local_path = local_paths[0]
local_path_info, err := os.Stat(local_path)
if err != nil {
return err
}
if !local_path_info.IsDir() {
return errors.New("local path not is dir")
}
}
if remote_path_info.IsDir() {
return obj.DownloadDir(remote_path, path.Join(local_path, remote_path_info.Name()))
}
return obj.DownloadFile(remote_path, path.Join(local_path, remote_path_info.Name()))
}
func (obj *Sftp) DownloadFile(remote_path string, local_path string) error {
remote_file, err := obj.client.Open(remote_path)
if err != nil {
return err
}
defer remote_file.Close()
dstFile, err := os.Create(local_path)
if err != nil {
return err
}
defer dstFile.Close()
_, err = remote_file.WriteTo(dstFile)
return err
}
func (obj *Sftp) DownloadDir(remote_path string, local_path string) error {
err := tools.MkDir(local_path)
if err != nil {
return err
}
remotefiles, err := obj.client.ReadDir(remote_path)
if err != nil {
return err
}
for _, remotefile := range remotefiles {
if remotefile.IsDir() {
err := obj.DownloadDir(obj.client.Join(remote_path, remotefile.Name()), path.Join(local_path, remotefile.Name()))
if err != nil {
return err
}
} else {
err := obj.DownloadFile(obj.client.Join(remote_path, remotefile.Name()), path.Join(local_path, remotefile.Name()))
if err != nil {
return err
}
}
}
return nil
}
func (obj *Sftp) Close() error {
return obj.client.Close()
}