nyan102 commited on
Commit
4414942
·
verified ·
1 Parent(s): 06e161c

Create ssh.py

Browse files
Files changed (1) hide show
  1. ssh.py +123 -0
ssh.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import socket
2
+ import sys
3
+ import threading
4
+ import paramiko
5
+ import select
6
+ import time
7
+
8
+ # 配置参数
9
+ USERNAME = 'Vme50RMB'
10
+ PASSWORD = f'{ssh_pass}'
11
+ HOST = 'lovedraw.cn'
12
+ REMOTE_PORT = 7865
13
+ LOCAL_HOST = '127.0.0.1'
14
+ LOCAL_PORT = 7865
15
+ KEEP_ALIVE_INTERVAL = 30 # 发送保持连接的间隔时间(秒)
16
+
17
+ # 定义一个类来处理转发请求
18
+ class ReverseForwardServer(threading.Thread):
19
+ def __init__(self, transport, remote_port, local_host, local_port):
20
+ super(ReverseForwardServer, self).__init__()
21
+ self.transport = transport
22
+ self.remote_port = remote_port
23
+ self.local_host = local_host
24
+ self.local_port = local_port
25
+ self.daemon = True # 使线程随主线程退出
26
+ self.start()
27
+
28
+ def run(self):
29
+ # 请求远程端口转发
30
+ try:
31
+ self.transport.request_port_forward('', self.remote_port)
32
+ print(f"请求在远程服务器上监听端口 {self.remote_port},转发到本地 {self.local_host}:{self.local_port}")
33
+ except Exception as e:
34
+ print(f'无法请求远程端口转发: {e}')
35
+ sys.exit(1)
36
+
37
+ while True:
38
+ try:
39
+ chan = self.transport.accept(1000) # 等待新连接,超时1秒
40
+ if chan is None:
41
+ continue
42
+ thr = threading.Thread(target=self.handle_channel, args=(chan,))
43
+ thr.daemon = True
44
+ thr.start()
45
+ except Exception as e:
46
+ print(f"处理通道时发生错误: {e}")
47
+ break
48
+
49
+ def handle_channel(self, chan):
50
+ try:
51
+ # 连接到本地服务
52
+ sock = socket.socket()
53
+ sock.connect((self.local_host, self.local_port))
54
+ except Exception as e:
55
+ print(f"无法连接到本地服务 {self.local_host}:{self.local_port}: {e}")
56
+ chan.close()
57
+ return
58
+
59
+ print(f"建立连接: {chan.origin_addr} -> {self.local_host}:{self.local_port}")
60
+
61
+ # 双向转发数据
62
+ def forward(src, dst):
63
+ try:
64
+ while True:
65
+ data = src.recv(1024)
66
+ if not data:
67
+ break
68
+ dst.sendall(data)
69
+ except Exception:
70
+ pass
71
+ finally:
72
+ src.close()
73
+ dst.close()
74
+
75
+ # 启动两个线程进行数据转发
76
+ t1 = threading.Thread(target=forward, args=(chan, sock))
77
+ t2 = threading.Thread(target=forward, args=(sock, chan))
78
+ t1.daemon = True
79
+ t2.daemon = True
80
+ t1.start()
81
+ t2.start()
82
+
83
+ def main():
84
+ while True: # 自动重连循环
85
+ client = paramiko.SSHClient()
86
+ client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 自动添加主机密钥
87
+
88
+ try:
89
+ print(f"正在连接到 {HOST}...")
90
+ client.connect(hostname=HOST, username=USERNAME, password=PASSWORD)
91
+ print("连接成功!")
92
+
93
+ transport = client.get_transport()
94
+ if transport is None or not transport.is_active():
95
+ print("SSH Transport不可用")
96
+ raise Exception("SSH Transport不可用")
97
+
98
+ # 设置保持连接(发送心跳)
99
+ transport.set_keepalive(KEEP_ALIVE_INTERVAL)
100
+ print(f"已设置保持连接,每 {KEEP_ALIVE_INTERVAL} 秒发送一次心跳包")
101
+
102
+ # 启动反向端口转发服务器
103
+ ReverseForwardServer(transport, REMOTE_PORT, LOCAL_HOST, LOCAL_PORT)
104
+
105
+ print(f"已在远程服务器 {HOST} 上监听端口 {REMOTE_PORT},并转发到本地 {LOCAL_HOST}:{LOCAL_PORT}")
106
+
107
+ # 保持主线程运行,并监控连接状态
108
+ while transport.is_active():
109
+ time.sleep(1)
110
+
111
+ except KeyboardInterrupt:
112
+ print("用户中断,关闭连接。")
113
+ break
114
+ except Exception as e:
115
+ print(f"发生错误: {e}")
116
+ print("尝试重新连接...")
117
+ time.sleep(5) # 等待5秒后重试
118
+ finally:
119
+ client.close()
120
+ print("SSH连接已关闭。")
121
+
122
+ if __name__ == "__main__":
123
+ main()