python创建TCP代理

1. 代理服务器

  1 # coding:utf8
  2 # 创建一个 TCP 代理
  3 
  4 import sys
  5 import socket
  6 import threading
  7 
  8 def server_loop(local_host, local_port, remote_host, remote_port, receive_first):
  9 
 10     server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 11     try:
 12         # 服务器监听的 host和端口
 13         server.bind((local_host, local_port))
 14     except Exception, e:
 15         print "[!!] Failed to listen on %s:%d" % (local_host, local_port)
 16         print "[!!] Check for other listening sockets or correct permissions"
 17         sys.exit(0)
 18     
 19     print "[*] Listening on %s:%d" % (local_host, local_port)
 20     
 21     #开始监听TCP传入连接
 22     server.listen(5)
 23 
 24     while True:
 25         # 获取客户端请求过来的数据
 26         client_socket, addr = server.accept()
 27 
 28         # 打印出本地客户端连接的信息
 29         print "[==>] Received incoming connection from %s:%d" % (addr[0], addr[1])
 30         
 31         # 开启一个线程 与 远程主机通信
 32         proxy_thread = threading.Thread(target=proxy_handler, args=(client_socket, remote_host, remote_port, receive_first))
 33         
 34         proxy_thread.start()
 35 
 36 
 37 # 十六进制转储的函数
 38 def hexdump(src, length=16):
 39     result = []
 40     digits = 4 if isinstance(src, unicode) else 2
 41 
 42     for i in xrange(0, len(src), length):
 43         s = src[i:i+length]
 44         hexa = b' ' . join(["%0*X" % (digits, ord(x)) for x in s])
 45         text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
 46         result.append(b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text))
 47 
 48     print b'
'.join(result)
 49 
 50 # 从远程服务器里面接受数据
 51 def receive_from(connection):
 52     print "receive_from function start ........... "
 53     buffer = ""
 54 
 55     # 我们设置了两秒的超时, 这取决于目标的情况, 可能需要调整
 56     connection.settimeout(2)
 57 
 58     try:
 59         # 持续从缓存中读取数据直到没有数据或者超时
 60         while True:
 61             data = connection.recv(4096)
 62             print "receive_from data is %s " % data
 63             if not data:
 64                 print "receive_from data is break ......."
 65                 break
 66 
 67             buffer += data
 68 
 69     except Exception, e:
 70         print str(e)
 71         print str(Exception)
 72         print 'error for receive_from'
 73 
 74     return buffer
 75 
 76 # 对目标是远程主机的请求进行修改
 77 def request_handler(buffer):
 78     #执行包修改
 79     return buffer
 80 
 81 # 对目标是本地主机的响应进行修改
 82 def response_handler(buffer):
 83     #执行包修改
 84     return buffer
 85     
 86 
 87 
 88 def proxy_handler(client_socket, remote_host, remote_port, receive_first):
 89     # 连接远程主机
 90     remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 91 
 92     print "remote_socket start ...... %s %d" % (remote_host, remote_port)
 93     remote_socket.connect((remote_host, remote_port))
 94 
 95     # 如果必要从远程主机接收数据
 96     if receive_first:
 97         remote_buffer = receive_from(remote_socket)
 98         hexdump(remote_buffer)
 99 
100         # 发送给我们的响应处理
101         remote_buffer = response_handler(remote_buffer)
102 
103         # 如果我们有数据传递给本地客户端,发送它
104         if len(remote_buffer):
105             print "[<==] Sending %d bytes to localhost." % len(remote_buffer)
106             client_socket.send(remote_buffer)
107 
108     # 现在我们从本地循环读取数据, 发送给远处主机和本地主机
109     while True:
110         # 从本地读取数据
111         local_buffer = receive_from(client_socket)
112         print "local_buffer is %s " % local_buffer
113         if len(local_buffer):
114             print "[==>] Received %d bytes from localhost." % len(local_buffer)
115             hexdump(local_buffer)
116 
117             # 这里可以改变我们请求的数据 过滤等功能
118             local_buffer = request_handler(local_buffer)
119 
120             # 向远处主机发送数据
121             remote_socket.send(local_buffer)
122             print "[==>] Sent to remote."
123 
124         # 接收响应的数据
125         remote_buffer = receive_from(remote_socket)
126         if len(remote_buffer):
127             print "[<==] Received %d bytes from remote." % len(remote_buffer) 
128             hexdump(remote_buffer)
129 
130             # 发送到响应处理函数
131             remote_buffer = response_handler(remote_buffer)
132 
133             # 将响应发送给本地socket
134             client_socket.send(remote_buffer)
135 
136         # 如果两边都没有数据, 关闭连接
137         if not len(local_buffer) or not len(remote_buffer):
138             client_socket.close()
139             remote_socket.close()
140             print "[*] No more data. Closing connections."
141             sys.exit(0)
142             break
143 
144         
145 
146 def main():
147     if len(sys.argv[1:]) != 5:
148         print "Usage: ./proxy.py [localhost] [localport] [remotehost] [remoteport] [receive_first]"
149         print "Example: ./proxy.py 127.0.0.1 9000 10.12.132.1 9000 True"
150         sys.exit(0)
151 
152     # 设置本地监听参数
153     local_host = sys.argv[1]
154     local_port = int(sys.argv[2])
155 
156     # 设置远程目标
157     remote_host = sys.argv[3]
158     remote_port = int(sys.argv[4])
159 
160     # 告诉代理在发送给远程主机之前连接和接受数据
161     receive_first = sys.argv[5]
162 
163     if "True" in receive_first:
164         receive_first = True
165     else:
166         receive_first = False
167 
168     # 设置好我们的监听 socket
169     server_loop(local_host, local_port, remote_host, remote_port, receive_first)
170 
171 main()
172 
173 
174 ##
175 ##python index5.py 0.0.0.0 9999 120.25.249.52 80 True
176 ##cd D:python_codehttPython

这是我们的代理服务器,如果是在本地调试的话,电脑是windows系统.

python index5.py 0.0.0.0 9999 120.25.249.52 80 True  监听本地电脑的9999端口 然后发收到的信息发送到
120.25.249.52:80里面获取网页信息,120.25.249.52这个是我自己的网站。

2. TCP客户端

 1 # coding:utf8
 2 
 3 import socket
 4 
 5 target_host = '127.0.0.1'
 6 target_port = 9999
 7 
 8 # 建立一个socket 对象 
 9 # socket.AF_INET表示IPv4地址,或者主机名
10 # socket.SCOK_STREAM 这将是一个TCP客户端
11 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 
13 # 连接客户端
14 client.connect((target_host, target_port))
15 
16 # 发送一些数据
17 client.send("GET / HTTP/1.1
Host: chengzhier.com

") # 这里不要直接打字符串,需要用http的形式请求 
18 
19 # 接收一些数据
20 response = client.recv(4096)
21 
22 print response


 

原文地址:https://www.cnblogs.com/shaoshao/p/8720146.html