81 lines
2.2 KiB
Python
81 lines
2.2 KiB
Python
import socket
|
||
import threading
|
||
import sys
|
||
|
||
TARGET_HOST = 'superstar.geelytravel.com'
|
||
TARGET_PORT = 443
|
||
|
||
def handle_request(sock):
|
||
"""处理从A设备收到的请求,转发到目标网站"""
|
||
try:
|
||
# 接收来自A设备的请求
|
||
request = b""
|
||
while True:
|
||
data = sock.recv(4096)
|
||
if not data:
|
||
break
|
||
request += data
|
||
if b"\r\n\r\n" in request:
|
||
break
|
||
|
||
if not request:
|
||
return
|
||
|
||
# 连接到目标网站
|
||
target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
target_sock.connect((TARGET_HOST, TARGET_PORT))
|
||
|
||
# 发送请求
|
||
target_sock.send(request)
|
||
|
||
# 接收响应并转发回A设备
|
||
while True:
|
||
response = target_sock.recv(4096)
|
||
if not response:
|
||
break
|
||
sock.send(response)
|
||
|
||
target_sock.close()
|
||
except Exception as e:
|
||
print(f"处理请求出错: {e}")
|
||
try:
|
||
sock.send(b"HTTP/1.1 500 Internal Server Error\r\n\r\n")
|
||
except:
|
||
pass
|
||
|
||
def connect_to_a_device(a_host, a_port):
|
||
"""连接到A设备"""
|
||
while True:
|
||
try:
|
||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||
sock.connect((a_host, a_port))
|
||
print(f"成功连接到A设备: {a_host}:{a_port}")
|
||
print(f"准备转发请求到: {TARGET_HOST}:{TARGET_PORT}")
|
||
|
||
handle_request(sock)
|
||
|
||
sock.close()
|
||
print("与A设备的连接已断开")
|
||
except ConnectionRefusedError:
|
||
print(f"A设备未就绪,重试中...")
|
||
import time
|
||
time.sleep(3)
|
||
except Exception as e:
|
||
print(f"连接出错: {e}")
|
||
import time
|
||
time.sleep(3)
|
||
|
||
def main():
|
||
if len(sys.argv) < 3:
|
||
print("用法: python proxy_client.py <A设备IP> <A设备端口>")
|
||
print("示例: python proxy_client.py 192.168.1.50 8080")
|
||
sys.exit(1)
|
||
|
||
a_host = sys.argv[1]
|
||
a_port = int(sys.argv[2])
|
||
|
||
connect_to_a_device(a_host, a_port)
|
||
|
||
if __name__ == '__main__':
|
||
main()
|