-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathforward.go
122 lines (106 loc) · 2.63 KB
/
forward.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
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"io"
"log"
"net"
"sync"
"time"
)
const (
//本地监听地址
laddr = "localhost:8800"
//远程服务地址
raddr = "localhost:80"
sshaddr = "localhost:222"
)
/*
*
基于ssh连接的端口转发
https://tools.ietf.org/html/rfc4254#page-16 TCP/IP Port Forwarding
通过ssh隧道将远程服务器(localhost)上的80端口映射到本地8800端口
*/
func main() {
sshConfig := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
ssh.Password("123456"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
ClientVersion: "",
Timeout: 10 * time.Second,
}
//监听本地映射端口
listener, err := net.Listen("tcp", laddr)
if err != nil {
log.Fatalln(err.Error())
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
continue
}
//客户端连接
go portForward(conn, sshConfig)
}
}
/*
*
conn: 客户端到本地映射端口的连接
sshConfig: ssh配置
*/
func portForward(conn net.Conn, sshConfig *ssh.ClientConfig) {
defer conn.Close()
//建立与SSH服务器的连接
sshClient, err := ssh.Dial("tcp", sshaddr, sshConfig)
if err != nil {
log.Fatalln(err.Error())
}
defer sshClient.Close()
//建立ssh到后端服务的连接
forwardConn, err := sshClient.Dial("tcp", raddr)
if err != nil {
log.Fatalln(err.Error())
}
log.Println("ssh端口映射隧道建立成功")
defer forwardConn.Close()
var wait2close = sync.WaitGroup{}
wait2close.Add(1)
go func() {
n, err := io.Copy(forwardConn, conn)
if err != nil {
log.Fatalln(err.Error())
wait2close.Done()
}
log.Printf("入流量共%s", formatFlowSize(n))
}()
go func() {
n, err := io.Copy(conn, forwardConn)
if err != nil {
log.Fatalln(err.Error())
wait2close.Done()
}
log.Printf("出流量共%s", formatFlowSize(n))
}()
wait2close.Wait()
log.Println("ssh端口映射隧道关闭")
}
// 字节的单位转换 保留两位小数
func formatFlowSize(s int64) (size string) {
if s < 1024 {
return fmt.Sprintf("%.2fB", float64(s)/float64(1))
} else if s < (1024 * 1024) {
return fmt.Sprintf("%.2fKB", float64(s)/float64(1024))
} else if s < (1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fMB", float64(s)/float64(1024*1024))
} else if s < (1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fGB", float64(s)/float64(1024*1024*1024))
} else if s < (1024 * 1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fTB", float64(s)/float64(1024*1024*1024*1024))
} else { //if s < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
return fmt.Sprintf("%.2fEB", float64(s)/float64(1024*1024*1024*1024*1024))
}
}