ACCC1380 commited on
Commit
0510a83
·
verified ·
1 Parent(s): 811e25b

Upload forward.py

Browse files
Files changed (1) hide show
  1. forward.py +268 -0
forward.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ import os
4
+ import importlib
5
+ import site
6
+ import socket
7
+ import threading
8
+ import time
9
+ import argparse
10
+
11
+ # 强制刷新 sys.path
12
+ importlib.reload(site)
13
+
14
+ import paramiko
15
+
16
+
17
+ # 配置参数
18
+ USERNAME = os.environ.get("SSH_USERNAME", "")
19
+ PASSWORD = os.environ.get("SSH_PASSWORD", "")
20
+ HOST = os.environ.get("SSH_HOST", "")
21
+ SSH_PORT = int(os.environ.get("SSH_PORT", "22"))
22
+
23
+ REMOTE_PORT = int(os.environ.get("SSH_REMOTE", "65534"))
24
+ LOCAL_HOST = "127.0.0.1"
25
+ LOCAL_PORT = int(os.environ.get("SSH_LOCAL", "28000"))
26
+
27
+ KEEP_ALIVE_INTERVAL = 60
28
+
29
+
30
+ def parse_args():
31
+ parser = argparse.ArgumentParser(
32
+ description="SSH 反向端口转发"
33
+ )
34
+
35
+ parser.add_argument(
36
+ "--listen",
37
+ action="store_true",
38
+ help="允许转发机监听所有网卡地址 0.0.0.0"
39
+ )
40
+
41
+ return parser.parse_args()
42
+
43
+
44
+ class ReverseForwardServer(threading.Thread):
45
+ def __init__(
46
+ self,
47
+ transport,
48
+ remote_bind_host,
49
+ remote_port,
50
+ local_host,
51
+ local_port
52
+ ):
53
+ super().__init__(daemon=True)
54
+
55
+ self.transport = transport
56
+ self.remote_bind_host = remote_bind_host
57
+ self.remote_port = remote_port
58
+ self.local_host = local_host
59
+ self.local_port = local_port
60
+
61
+ self.start()
62
+
63
+ def run(self):
64
+ try:
65
+ allocated_port = self.transport.request_port_forward(
66
+ self.remote_bind_host,
67
+ self.remote_port
68
+ )
69
+
70
+ print(
71
+ f"请求远程服务器监听 "
72
+ f"{self.remote_bind_host}:{allocated_port},"
73
+ f"转发到本地 "
74
+ f"{self.local_host}:{self.local_port}"
75
+ )
76
+
77
+ except Exception as e:
78
+ print(f"无法请求远程端口转发: {e}")
79
+ return
80
+
81
+ while self.transport.is_active():
82
+ try:
83
+ chan = self.transport.accept(1)
84
+
85
+ if chan is None:
86
+ continue
87
+
88
+ threading.Thread(
89
+ target=self.handle_channel,
90
+ args=(chan,),
91
+ daemon=True,
92
+ ).start()
93
+
94
+ except Exception as e:
95
+ print(f"处理通道时发生错误: {e}")
96
+ break
97
+
98
+ def handle_channel(self, chan):
99
+ try:
100
+ sock = socket.create_connection(
101
+ (
102
+ self.local_host,
103
+ self.local_port
104
+ )
105
+ )
106
+
107
+ except Exception as e:
108
+ print(
109
+ f"无法连接到本地服务 "
110
+ f"{self.local_host}:{self.local_port}: {e}"
111
+ )
112
+
113
+ chan.close()
114
+ return
115
+
116
+ print(
117
+ f"建立连接: "
118
+ f"{chan.origin_addr} -> "
119
+ f"{self.local_host}:{self.local_port}"
120
+ )
121
+
122
+ def forward(src, dst):
123
+ try:
124
+ while True:
125
+ data = src.recv(65536)
126
+
127
+ if not data:
128
+ break
129
+
130
+ dst.sendall(data)
131
+
132
+ except Exception:
133
+ pass
134
+
135
+ finally:
136
+ try:
137
+ src.close()
138
+ except Exception:
139
+ pass
140
+
141
+ try:
142
+ dst.close()
143
+ except Exception:
144
+ pass
145
+
146
+ threading.Thread(
147
+ target=forward,
148
+ args=(chan, sock),
149
+ daemon=True,
150
+ ).start()
151
+
152
+ threading.Thread(
153
+ target=forward,
154
+ args=(sock, chan),
155
+ daemon=True,
156
+ ).start()
157
+
158
+
159
+ def main():
160
+ args = parse_args()
161
+
162
+ # 默认只允许转发机本机访问
163
+ remote_bind_host = "127.0.0.1"
164
+
165
+ # 带 --listen 时监听所有 IPv4 地址
166
+ if args.listen:
167
+ remote_bind_host = "0.0.0.0"
168
+
169
+ print(
170
+ f"远程监听模式: "
171
+ f"{remote_bind_host}:{REMOTE_PORT}"
172
+ )
173
+
174
+ if args.listen:
175
+ print(
176
+ "已启用 --listen,"
177
+ "远程端口将尝试监听所有网卡。"
178
+ )
179
+ print(
180
+ "注意:SSH 服务端需要配置 "
181
+ "GatewayPorts clientspecified"
182
+ )
183
+ else:
184
+ print(
185
+ "未启用 --listen,"
186
+ "远程端口仅允许转发机本机访问。"
187
+ )
188
+
189
+ while True:
190
+ client = paramiko.SSHClient()
191
+
192
+ client.set_missing_host_key_policy(
193
+ paramiko.AutoAddPolicy()
194
+ )
195
+
196
+ try:
197
+ print(
198
+ f"正在连接到 "
199
+ f"{HOST}:{SSH_PORT}..."
200
+ )
201
+
202
+ client.connect(
203
+ hostname=HOST,
204
+ port=SSH_PORT,
205
+ username=USERNAME,
206
+ password=PASSWORD,
207
+ )
208
+
209
+ print("连接成功!")
210
+
211
+ transport = client.get_transport()
212
+
213
+ if (
214
+ transport is None
215
+ or not transport.is_active()
216
+ ):
217
+ raise RuntimeError(
218
+ "SSH Transport 不可用"
219
+ )
220
+
221
+ transport.set_keepalive(
222
+ KEEP_ALIVE_INTERVAL
223
+ )
224
+
225
+ print(
226
+ f"已设置保持连接,每 "
227
+ f"{KEEP_ALIVE_INTERVAL} 秒"
228
+ "发送一次心跳包"
229
+ )
230
+
231
+ ReverseForwardServer(
232
+ transport,
233
+ remote_bind_host,
234
+ REMOTE_PORT,
235
+ LOCAL_HOST,
236
+ LOCAL_PORT,
237
+ )
238
+
239
+ print(
240
+ f"远程监听 "
241
+ f"{HOST}:{REMOTE_PORT} "
242
+ f"({remote_bind_host})"
243
+ )
244
+
245
+ print(
246
+ f"转发目标 "
247
+ f"{LOCAL_HOST}:{LOCAL_PORT}"
248
+ )
249
+
250
+ while transport.is_active():
251
+ time.sleep(1)
252
+
253
+ except KeyboardInterrupt:
254
+ print("用户中断,关闭连接。")
255
+ break
256
+
257
+ except Exception as e:
258
+ print(f"发生错误: {e}")
259
+ print("5 秒后尝试重新连接...")
260
+ time.sleep(5)
261
+
262
+ finally:
263
+ client.close()
264
+ print("SSH 连接已关闭。")
265
+
266
+
267
+ if __name__ == "__main__":
268
+ main()