-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1965 lines (1847 loc) · 49.1 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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
/*
Как собрать:
`git clone https://github.com/abakum/dssh`
`cd dssh`
Копируем секретный dssh.zip в .
В нём:
ключ шифрования вложений `key.enc`,
секретный алгоритм извлечения ключа шифрования вложений в `internal\tool\tool.go` (не показывай никому),
ключ Центра Сертификации `internal\ca`. Его можно обновлять запуском `go run cmd/main.go`
`unzip -a dssh.zip`
`go run github.com/abakum/embed-encrypt` этим генерируется код для вложений `encrypted_fs.go`
`go install`
Запускаем `dssh -v` как сервис. Первый раз с `-v`. Если указан параметр `-v` или `--debug` то на всякий случай создаются копии старых файлов .old
Обязательно запускаем `dssh :` как клиента через посредника `dssh@ssh-j.com` на хосте за NAT.
В файл ~/.ssh/config дописываются алиасы хостов dssh, ssh-j, ssh-j.com.
Создаются файлы известных хостов `~/.ssh/ssh-j` (по запросу) и `~/.ssh/dssh`
Если агент ключей получает ключ id_x то создаётся сертификат `~/.ssh/id_x-cert.pub`
Без этого файла и доступа к агенту ключей в момент запуска доступ к dssh-серверу через putty или ssh не возможен.
Если указан параметр `-u` или `--putty` то:
Создаются файлы сессий из `~/.ssh/config` в `~/.putty/sessions`
Создаётся сертификат хоста в `~/.putty/sshhostcas`
Тоже самое и для Windows из %USERPROFILE%\.ssh\config в реестр CURRENT_USER\SOFTWARE\SimonTatham\PuTTY
*/
import (
"bytes"
"context"
"crypto/x509"
_ "embed"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/abakum/embed-encrypt/encryptedfs"
"github.com/abakum/go-ser2net/pkg/ser2net"
"github.com/abakum/go-serial"
"github.com/abakum/go-stun/stun"
"github.com/abakum/menu"
"github.com/abakum/winssh"
"github.com/containerd/console"
"github.com/mattn/go-isatty"
"github.com/ncruces/rethinkraw/pkg/chrome"
"github.com/pkg/browser"
"github.com/trzsz/go-arg"
"github.com/trzsz/ssh_config"
"github.com/unixist/go-ps"
. "github.com/abakum/dssh/tssh"
version "github.com/abakum/version/lib"
"github.com/xlab/closer"
"golang.org/x/crypto/ssh"
)
type Parser struct {
*arg.Parser
}
func (p *Parser) WriteHelp(w io.Writer) {
var b bytes.Buffer
p.Parser.WriteHelp(&b)
s := strings.Replace(b.String(), " -v, --version show program's version number and exit\n", "", 1)
fmt.Fprint(w, s)
}
func NewParser(config arg.Config, dests ...interface{}) (*Parser, error) {
p, err := arg.NewParser(config, dests...)
return &Parser{p}, err
}
const (
ALL = "0.0.0.0"
LH = "127.0.0.1"
FILEMODE = 0644
DIRMODE = 0755
TOR = time.Second * 15 //reconnect TO
TOW = time.Second * 5 //watch TO
SSH2 = "SSH-2.0-"
OSSH = "OpenSSH_for_Windows"
RESTART = "--restart"
SSHJ = "ssh-j"
SSHJ2 = LH
JumpHost = SSHJ + ".com"
PORTT = 5000
PORTW = 8000
PORTS = 2200
PORTV = 5500
LockFile = "lockfile"
SEP = ","
)
var (
_ = encryptedfs.ENC
_ = version.Ver
SshUserDir = winssh.UserHomeDirs(".ssh")
Cfg = filepath.Join(SshUserDir, "config")
KnownHosts = filepath.Join(SshUserDir, "known_hosts")
args SshArgs
Std = menu.Std
repo = base() // Имя репозитория `dssh` оно же имя алиаса в .ssh/config
rev = revision() // Имя для посредника.
imag string // Имя исполняемого файла `dssh` его можно изменить чтоб не указывать имя для посредника.
Windows = runtime.GOOS == "windows"
Cygwin = isatty.IsCygwinTerminal(os.Stdin.Fd())
Win7 = isWin7() // Windows 7 не поддерживает ENABLE_VIRTUAL_TERMINAL_INPUT и ENABLE_VIRTUAL_TERMINAL_PROCESSING
once,
SP bool
ZerroNewWindow = os.Getenv("SSH_CONNECTION") != ""
tmp = filepath.Join(os.TempDir(), repo)
ips = ser2net.Ints()
EED = "<Enter>~."
EEDE = EED
ioc = ser2net.ReadWriteCloser{Reader: os.Stdin, WriteCloser: os.Stdout, Cygwin: Cygwin}
listen = strconv.Itoa(PORTS)
tt *time.Timer
eips []string
)
//go:generate go run github.com/abakum/version
//go:generate go run cmd/main.go
//go:generate go run github.com/abakum/embed-encrypt
//go:generate go list -f '{{.EmbedFiles}}'
//encrypted:embed internal/ca
var CA []byte // Ключ ЦС
//go:embed VERSION
var Ver string
// `dssh` `dssh -d` `dssh -l revision` `revision` Где revision это что-то типа 59d7a68 (смотри `dssh -V`)
//
// запустит сервер ssh на адресе `127.0.0.1:2222`.
// подготовит алиас `ssh-j.com` и запустит его для переноса сессии с белого адреса `ssh-j.com:22` на серый `127.0.0.1:2222`.
// подготовит алиас `dssh` для подключения к серверу локально.
// подготовит алиас `ssh-j` для подключения к серверу через `dssh@ssh-j.com`.
// `dssh .` `dssh dssh` `ssh dssh` подключится к серверу локально.
// `dssh :` `dssh ssh-j` `revision :` `dssh -l revision ssh-j` `ssh ssh-j` подключится к серверу через посредника `revision@ssh-j.com`.
func main() {
SetColor()
// tssh
DebugF = func(format string) string {
return fmt.Sprintf("%s%s %s\r\n", l.Prefix(), src(9), format)
}
WarningF = func(format string) string {
return fmt.Sprintf("%s%s %s\r\n", le.Prefix(), src(9), format)
}
exe, err := os.Executable()
Fatal(err)
imag = strings.Split(filepath.Base(exe), ".")[0]
Println(build(Ver, ips))
if ips[0] == LH {
Println(fmt.Errorf("not connected - нет сети"))
}
anyKey, err := x509.ParsePKCS8PrivateKey(CA)
Fatal(err)
// CA signer
signer, err := ssh.NewSignerFromKey(anyKey)
Fatal(err)
// Like `parser := arg.MustParse(&args)` but override built in option `-v, --version` of package `arg`
// parser, err := NewParser(arg.Config{Out: io.Discard, Exit: func(int) {}}, &args)
parser, err := NewParser(arg.Config{}, &args)
Fatal(err)
a2s := []string{} // Без встроенных параметров -h -v и без аргументов после args.Destination
lasts := []string{} // После args.Destination
command := false
errError := ""
for _, arg := range os.Args[1:] {
if command {
lasts = append(lasts, arg)
continue
}
switch arg {
case "-H":
arg = "--path"
case "-v":
arg = "--debug"
}
switch strings.ToLower(arg) {
case "--help":
parser.WriteHelp(Std)
return
case "-h":
parser.WriteUsage(Std)
return
case "-v", "--version":
Println(args.Version())
return
default:
a2s = append(a2s, arg)
}
args = SshArgs{}
err = parser.Parse(a2s) // Для определения args.Destination
if err != nil {
if errError == err.Error() {
break
}
ua := "unknown argument -"
if strings.HasPrefix(err.Error(), ua) {
ua = strings.TrimPrefix(err.Error(), ua)
if strings.Contains(strings.ToLower(ua), "h") {
// -ath
parser.WriteUsage(Std)
return
}
if strings.Contains(ua, "V") {
// -ATV
Println(args.Version())
return
}
}
// Println(arg, err)
errError = err.Error()
continue
}
if args.Destination != "" {
command = true
}
}
// Println(os.Args[0], a2s, lasts)
args = SshArgs{}
if err := parser.Parse(a2s); err != nil {
parser.WriteUsage(Std)
Fatal(err)
}
if args.Ver {
Println(args.Version())
return
}
args.Command = ""
args.Argument = []string{}
if len(lasts) > 0 {
// args.Command = as[0]
// args.Argument = as[1:]
// Так в Linux подставляются переменные среды
args.Command = strings.Join(lasts, " ")
// if args.ForceTTY {
// setRaw(&once)
// }
}
// log.SetFlags(lf.Flags() | log.Lmicroseconds)
log.SetFlags(lf.Flags())
log.SetPrefix(lf.Prefix())
if !args.Debug {
log.SetOutput(io.Discard)
}
// tools
SecretEncodeKey = key
if args.NewHost ||
args.EncSecret ||
args.InstallTrzsz ||
args.InstallPath != "" ||
args.TrzszVersion != "" ||
args.TrzszBinPath != "" ||
false {
Tssh(&args)
return
}
cli := fmt.Sprint(args.Option) != "{map[]}"
enableTrzsz := "yes"
switch strings.ToLower(args.EscapeChar) {
case "":
args.EscapeChar = "~"
case "none":
default:
enableTrzsz = "no"
}
args.Option.UnmarshalText([]byte("EscapeChar=" + args.EscapeChar))
EED = "<Enter>" + args.EscapeChar + "."
exit := " или <^D>"
if Windows {
exit = " или <^Z>"
}
EEDE = EED + exit
autoDirectJump := ""
autoDirectJumpOnce := false
// -j Это автообход посредника для dssh-сервера с внешним IP и `dssh +`
adj := func() (s string) {
cgi := exec.Command(repo, "-T", ":", repo, "-j")
cgi.Stdin = os.Stdin
cgi.Stderr = os.Stderr
output, err := cgi.Output()
Println(string(output), err)
if err != nil {
return
}
ips := strings.Split(string(output), SEP)
for _, ip := range ips {
if ip != LH && isHP(JoinHostPort(ip, PORTS)) {
Println("-j", ip)
return ip
}
}
return
}
if args.DirectJump && args.Destination == "" {
autoDirectJumpOnce = true
autoDirectJump = adj()
if autoDirectJump == "" {
Println(fmt.Errorf("auto directJump failed - без посредника не обойтись"))
args.DirectJump = false
args.Destination = "."
} else {
Println("directJump success - Дальше без посредника")
args.Destination = autoDirectJump
}
}
u, h, p := ParseDestination(args.Destination) //tssh
p = portPB(p, PORTS)
s2, dial := host2LD(h)
// `dssh` как `dssh -d`
// `foo` как `dssh foo@` как `dssh -dl foo`
if args.LoginName != "" {
u = args.LoginName // dssh -l foo
}
if u == "" {
u = rev // Имя для посредника ssh-j.com
if imag != repo {
u = imag // Если бинарный файл переименован то вместо ревизии имя переименованного бинарного файла и будет именем для посредника ssh-j.com
}
}
tmpU := filepath.Join(tmp, u)
dot := psPrint(filepath.Base(exe), "", 0, PrintNil) > 1 && isFileExist(tmpU)
portT := portOB(args.Ser2net, PORTT)
portW := portOB(args.Ser2web, PORTW)
portV := portOB(args.VNC, PORTV)
argsShare := args.Share
if args.Share {
// Отдаём свою консоль через dssh-сервер
portT, portW = optS(portT, portW)
if args.Destination == "" || isDssh() {
// -s
// -s .
// -s :
args.Share = !(dot || args.Destination == "")
args.Destination = ":"
if !args.Share {
args.Destination = ""
}
}
}
emptyCommand := args.Command == "" && !args.NoCommand
if args.Use {
if args.Destination == "" || isDssh() {
portT, portW = optS(portT, portW)
// Используем консоль dssh-сервера
// -0
// -0 .
// -0 :
if !dot {
args.Destination = ":"
// -20 :
}
} else {
if emptyCommand {
// -0 X
// Используем консоль sshd-сервера X
portT, portW = optS(portT, portW)
// X dssh -HH -UU -22 -88
} else {
args.Use = false
Println(fmt.Errorf("option -0 only used without command - ключ -0 используется только если нет команды"))
// X command
}
}
}
// Заменяем `dssh .` на `dssh :` если на хосте не запущен dssh-сервер
switch args.Destination {
case ".", repo:
if !dot {
args.Destination = ":"
}
}
loc := localHost(args.Destination)
optL(portT, &args, s2, loc, dot)
optL(portW, &args, s2, loc, dot)
external := args.Putty || args.Telnet
switch args.Serial {
case "H":
args.Serial = ":"
if args.Destination == "" && !isHP(JoinHostPort(LH, PORTT)) {
args.Destination = ":"
if dot {
args.Destination = "."
}
} else if isDssh() {
args.Serial = ""
if portT < 0 {
portT = PORTT
}
}
case "_", "+":
args.Serial += ":"
}
if strings.HasSuffix(args.Serial, ":") {
args.Serial += strconv.Itoa(PORTT)
}
if args.Baud == "" {
if args.Destination == "" && external || // -u || -Z
args.Unix && !external { // -z
args.Baud = "U"
}
}
vncDirect := portV > 0 && !loc
if vncDirect && isDssh() && !args.DirectJump {
// -70 : Это Показывающий подключается к Наблюдателю с внешним IP и `dssh +`
if !autoDirectJumpOnce {
autoDirectJump = adj()
}
if autoDirectJump == "" {
vncDirect = false
} else {
args.DirectJump = true
args.Destination = autoDirectJump
}
}
BSnw := args.Serial != "" || args.Baud != "" || portT > 0 || portW > 0 || vncDirect
if !loc && Win7 && !(args.DisableTTY || args.NoCommand || Cygwin || external || BSnw) {
s := PUTTY
_, err := exec.LookPath(s)
args.Putty = err == nil
if !args.Putty { //
s = SSH
_, err := exec.LookPath(s)
args.Telnet = err == nil
}
external = args.Putty || args.Telnet
if external {
Println(fmt.Errorf("trying to use - в Windows 7 пробую использовать " + s))
}
}
if args.Command != "" && args.Putty && !args.Unix {
Println(fmt.Errorf("for run will use - для запуска %q будем использовать plink", args.Command))
args.Unix = true
}
if Win7 && !(Cygwin || external) {
Println(fmt.Errorf("try to use - в Windows 7 попробуй использовать `-88`"))
}
djh := ""
djp := ""
if args.DirectJump {
dj := args.Destination
if strings.Count(dj, ":") == 0 {
dj += ":" + listen
}
djh, djp, err = net.SplitHostPort(dj)
if err == nil {
s2, dial = host2LD(djh)
djh = dial
// if args.Command != "" {
// args.Command = args.Destination + " " + args.Command
// }
args.Destination = repo // Не локальный
if djh == LH {
args.Destination = "." // Локальный
}
for _, ip := range ips {
if ip == djh {
args.Destination = "." // Локальный
break
}
}
if djp == "" {
djp = listen
}
} else {
Println(fmt.Errorf("error in param - ошибка в параметре `%s -j %s` %v", repo, args.Destination, err))
}
}
loc = localHost(args.Destination)
if Win7 && args.Telnet {
pe := func(s string) {
if args.Unix {
return
}
Println(fmt.Errorf("can't run in a separate window - не могу запускать " + s + " в отдельном окне на Windows 7"))
}
if loc {
pe(TELNET)
} else {
pe(SSH)
args.Unix = true
}
}
external = args.Putty || args.Telnet
signers, err := externalClient(&external, exe)
if err != nil {
Println(err)
}
ser, sw, sh, sp := swSerial(args.Serial)
SP = ser == "" || sw == "s"
if loc && Win7 && Cygwin && SP {
if args.Unix && args.Putty {
Println(fmt.Errorf("can't interrupt - не могу прервать plink в Cygwin на Windows 7"))
}
args.Unix = false
}
ZerroNewWindow = ZerroNewWindow || args.Unix
existsPuTTY := false
extSer := false
extTel := false
bins := []string{}
if !args.Telnet {
if ZerroNewWindow {
bins = []string{PLINK}
} else {
bins = []string{PUTTY, PLINK}
}
}
var execPath, bin string
if external {
_, err := exec.LookPath(TELNET)
if err == nil {
extTel = true
bins = append(bins, TELNET)
}
if !Windows {
_, err := exec.LookPath(BUSYBOX)
if err == nil {
if SP && !args.Telnet {
// putty plink busybox
extSer = exec.Command(BUSYBOX, MICROCOM, "--help").Run() == nil
} else {
// putty plink telnet
// putty plink busybox
if !extTel {
extTel = exec.Command(BUSYBOX, TELNET).Run() == nil
}
}
if extSer || extTel {
bins = append(bins, BUSYBOX)
}
}
}
// putty plink telnet - extTel
// putty plink busybox - extTel
// putty plink busybox - extSer
execPath, bin, err = look(bins...)
if err != nil {
if external {
Println(fmt.Errorf("not found - не найдены %v", bins))
}
} else {
switch bin {
case PUTTY, PLINK:
existsPuTTY = true
extSer = true
extTel = true
default:
if args.Putty {
Println(fmt.Errorf("not found - не найдены PuTTY, plink"))
}
}
}
}
external = extSer || extTel
if Cygwin {
// cygpath -w ~/.ssh
cygUserDir, err := cygpath("~")
if err != nil {
cygUserDir = "~"
}
cygUserDir = filepath.Join(cygUserDir, ".ssh")
Println(fmt.Sprintf(`You can make a link - Можно сделать ссылку 'mklink /d "%s" "%s"'`, cygUserDir, SshUserDir))
}
if external && loc {
switch sw {
case "t":
if isHP(ser) {
if portT < 0 || localHost(sh) {
portT = sp
}
} else {
Println(fmt.Errorf("not connected to - не удалось подключиться к %q", ser))
return
}
case "", "s":
if portT < 0 && !extSer {
portT = PORTT
}
case "c":
if portT < 0 {
portT = PORTT
}
}
}
BSnw = ser != "" || args.Baud != "" || portT > 0 || portW > 0 || vncDirect
var mode serial.Mode
if BSnw {
enableTrzsz = "no"
if loc || args.Destination == "." {
// Локальный последовательный порт
usbSerial := ""
usbSerial, mode = getFirstUsbSerial(ser, args.Baud, Print)
ser, sw, _, _ = swSerial(usbSerial)
SP = ser == "" || sw == "s"
BSnw = BSnw || ser != ""
portT = comm(ser, s2, portT, portW)
BSnw = BSnw || portT > 0 || portW > 0 || vncDirect
}
}
// Println(fmt.Sprintf("args %+v", args))
Println(os.Args[0], a2s, args.Command)
defer closer.Close()
closer.Bind(cleanup)
ctx, cancel := context.WithCancel(context.Background())
closer.Bind(cancel)
args.StdioForward = ser2net.LocalPort(args.StdioForward)
if args.StdioForward != "" && args.Destination == "" {
// Телнет сервер dssh -22
// Телнет клиент без RFC2217 dssh -W:5002
setRaw(&once)
forwardSTDio(ctx, ioc, args.StdioForward, EEDE, Println)
return
}
nw := func(s2, dial string) {
if portW > 0 {
if portT > 0 {
Println(repo, "-H", ser, "-2", portT)
go func() {
setRaw(&once)
Println(rfc2217(ctx, ioc, ser, s2, portT, args.Baud, exit, Println))
closer.Close()
}()
// Даже если -H: это может быть set2net или hub4com или RouterOS позволяющие только одного клиента
time.Sleep(time.Second)
ser = JoinHostPort(s2, portT)
}
Println(repo, "-H", ser, "-8", portW)
if hp := newHostPort(dial, portW, ser); isHP(hp.dest()) {
// Подключаемся к существующему сеансу
hp.read()
Println(hp.String())
go cancelByFile(ctx, cancel, hp.name(), TOW)
Println(ToExitPress, "<^C>")
Println(browse(ctx, dial, portW, cancel))
return
}
// Стартуем веб сервер
t := time.AfterFunc(time.Second*2, func() {
Println(browse(ctx, dial, portW, nil))
})
defer t.Stop() // Если не успел стартануть то и не надо
setRaw(&once)
if portT > 0 {
Println(s2w(ctx, nil, nil, ser, s2, portW, args.Baud, "", PrintNil))
} else {
Println(s2w(ctx, ioc, nil, ser, s2, portW, args.Baud, ". или ^C", Println))
}
} else {
Println(repo, "-H", ser, "-2", portT)
setRaw(&once)
Println(rfc2217(ctx, ioc, ser, s2, portT, args.Baud, exit, Println))
}
}
sshj := `
Host ` + SSHJ + ` :
User _
HostName ` + SSHJ2 + `
UserKnownHostsFile ~/.ssh/` + repo + `
KbdInteractiveAuthentication no
PasswordAuthentication no
RequestTTY yes
ProxyJump ` + u + `@` + JumpHost + `
EnableTrzsz ` + enableTrzsz
if args.Command == "" && (args.Restart || args.Stop || BSnw) {
// Println("CGI")
cli = true
// args.ForceTTY = true
args.Argument = []string{}
if args.Restart || args.Stop {
// dssh --restart
if args.Destination == "" {
args.Destination = ":" // Рестарт сервера за NAT
}
args.Command = repo
if args.Restart {
args.Argument = append(args.Argument, RESTART)
}
if args.Stop {
s := winssh.UserName()
hostname, err := os.Hostname()
if err == nil {
s += "@" + hostname
}
s += " " + winssh.Banner()
args.Argument = append(args.Argument, "--exit", s)
}
} else {
// Println("-UU || -HH || -22 || -88")
if loc {
Println("Local console - Локальная консоль", ser)
if external {
opt := ""
if portT > 0 {
opt = optTelnet(bin, dial, portT)
} else {
// mode := getMode(serial, args.Baud)
if !existsPuTTY && extSer {
opt = fmt.Sprintln(MICROCOM, "-s", mode.BaudRate, ser)
execPath = BUSYBOX
} else {
opt = fmt.Sprintln("-serial", ser, "-sercfg", fmt.Sprintf("%s,N", ser2net.Mode{Mode: mode}))
}
}
opts := strings.Fields(opt)
if args.Command != "" {
opts = append(opts, args.Command)
}
cmd := exec.CommandContext(ctx, execPath, opts...)
run := func() {
err = cmd.Start()
PrintLn(3, cmd, err)
cmd.Wait()
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
if portT > 0 {
if extTel && args.Telnet {
if !ZerroNewWindow && Windows {
if !Win7 {
createNewConsole(cmd)
Println(cmdRun(cmd, ctx, os.Stdin, false, ser, s2, portT, args.Baud, exit, Println))
return
}
}
// Println("-zZ || -zu && !existsPuTTY")
cmd.Stdin = os.Stdin
ec := "q"
if bin == BUSYBOX {
ec = "e"
}
exit := "<^Q>" + ec + "<Enter>"
if Cygwin && !Win7 {
exit = "<^C>"
}
Println(cmdRun(cmd, ctx, nil, false, ser, s2, portT, args.Baud, exit, PrintNil))
return
}
// !extTel || !args.Telnet
if ZerroNewWindow {
if bin == PLINK {
ConsoleCP()
} else {
Println("-zu22", fmt.Errorf("plink not found"))
return
}
// Println("-zu22")
Println(cmdRun(cmd, ctx, nil, true, ser, s2, portT, args.Baud, exit, Println))
return
}
if bin != PUTTY {
Println("-u22", fmt.Errorf("PuTTY not found"))
if bin == PLINK {
createNewConsole(cmd)
} else {
Println("-u22", fmt.Errorf("plink not found"))
return
}
}
// Println("-u22")
if Win7 && Cygwin {
exit = "<^Z><^Z>"
}
Println(cmdRun(cmd, ctx, os.Stdin, false, ser, s2, portT, args.Baud, exit, Println))
return
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
cmd.Stdin = os.Stdin
// Println("-u || -zu || extSer")
exit := "<^C>"
switch bin {
case PUTTY:
if Win7 && Cygwin {
exit = "[X] on window with - на окне с PuTTY"
}
case PLINK:
ConsoleCP()
default:
if extSer {
exit = "<^X>"
}
}
Println(ToExitPress, exit)
run()
return
}
// !external && loc
if portT > 0 || portW > 0 {
// Println("portT > 0 || portW > 0")
nw(s2, dial)
return
}
// Println("-HH || -Hcmd | -H:")
setRaw(&once)
Println(cons(ctx, ioc, ser, args.Baud, exit, Println))
return
}
}
}
cli = cli ||
fmt.Sprint(args.Identity) != "{[]}" ||
fmt.Sprint(args.DynamicForward) != "{[]}" ||
fmt.Sprint(args.LocalForward) != "{[]}" ||
fmt.Sprint(args.RemoteForward) != "{[]}" ||
args.Command != "" ||
args.ForwardAgent ||
args.NoForwardAgent ||
args.DisableTTY ||
args.ForceTTY ||
args.IPv4Only ||
args.IPv6Only ||
args.Gateway ||
args.Background ||
args.NoCommand ||
args.CipherSpec != "" ||
args.ConfigFile != "" ||
args.StdioForward != "" ||
args.X11Untrusted ||
args.NoX11Forward ||
args.X11Trusted ||
args.Reconnect ||
args.DragFile ||
args.TraceLog ||
args.Relay ||
args.Zmodem ||
args.Putty ||
args.DirectJump ||
false
if cli && args.Destination == "" {
args.Destination = "@"
}
daemon := false
switch args.Destination {
case "@": // Меню tssh.
args.Destination = ""
case ":", SSHJ: // `dssh :` как `dssh ssh-j` как `foo -l dssh :`
args.Destination = SSHJ
args.LoginName = "_"
case ".", repo: // `dssh .` как `dssh dssh` или `foo -l dssh .` как `foo -l dssh dssh`
args.Destination = repo
args.LoginName = "_"
// case "*", ALL, ips[len(ips)-1], "_", ips[0]:
// daemon = true
default:
daemon = localHost(args.Destination)
// switch h {
// case "*", ALL, ips[len(ips)-1], "_", ips[0]:
// daemon = true
// default:
// daemon = h+p == ""
// }
if !daemon {
daemon = h+p == listen
}
}
// Сервис.
if args.Daemon || !cli && daemon {
args.Daemon = true
hh := dial
h = s2
if p == listen {
if args.Port != 0 {
p = strconv.Itoa(args.Port)
}
}
client(signer, signers, local(hh, p, repo)+sshj+sshJ(JumpHost, u, hh, p))
args.Destination = JumpHost
time.AfterFunc(time.Second, func() {
s := fmt.Sprintf("`tssh %s`", JumpHost)
i := 0
hp := hh + ":" + p
if p == listen {
if hh == LH {
hp = ":"
} else {
hp = hh
}
} else {
if hh == LH {
hp = ":" + p
}
}
prox := "local or over jump host - локально или через посредника"
if s2 != ALL && s2 != LH {
prox = "local - локально"
}
var once sync.Once
for {
var ss, eip, m string
j := "`" + imag + " -j %s`"
if ips[0] != LH && hh != LH {
eip, m, err = GetExternalIP(time.Second, "stun.sipnet.ru:3478", "stun.l.google.com:19302", "stun.fitauto.ru:3478")
if err == nil {
Println(m)
ehp := eip + ":" + p
if p != listen {
eip = ehp
}
if isHP(ehp) {
ss = fmt.Sprintf("или WAN "+j, eip)
} else {
Println(fmt.Errorf("на роутере не настроен перенос %s->%s", ehp, hp))
}
}
}
Println("to connect use - чтоб подключится используй:")
Println(fmt.Sprintf("%s `%s .` over - через LAN "+j, prox, imag, hp), ss)
j = "\t`" + imag + " -u%s`"
if ss != "" {
ss = fmt.Sprintf(j, "j "+eip)
}
Println(fmt.Sprintf("\tPuTTY"+j+j, " .", "j "+hp) + ss)
j = "\t`" + imag + " -uz%s`"
if ss != "" {
ss = fmt.Sprintf(j, "j "+eip)
}
Println(fmt.Sprintf("\tplink"+j+j, " .", "j "+hp) + ss)
j = "\t`" + imag + " -Z%s`"
// Список слушающих IP для CGI -j
eips = []string{}
if ss != "" {
// WAN
ss = fmt.Sprintf(j, "j "+eip)
eips = append(eips, eip)
}
if s2 == ALL {
eips = append(eips, ips...)
} else {
eips = append(eips, s2)
}
Println(fmt.Sprintf("\tssh"+j+j, " .", "j "+hp) + ss)
lhListen := s2 == LH || s2 == ALL
if portV > 0 {