python socks5脚本

import socket
import threading,sys

def handle_client(client_socket):
    request = client_socket.recv(3)
    version, nmethods, methods = request[0], request[1], request[2:]
    response = b"\x05\x00"  # Version 5,版本协商
    client_socket.sendall(response)
    request = client_socket.recv(4)
    version, cmd, _, addr_type = request[0], request[1], request[2], request[3]
    if cmd != 1:
        client_socket.close()
        return
    if addr_type == 1:  # IPv4
        dest_addr = socket.inet_ntoa(client_socket.recv(4)) #接收四字节的数据,转换为ipv4点分制
    elif addr_type == 3:  # Domain name
        addr_len = int.from_bytes(client_socket.recv(1), byteorder='big') #接收一个字节的数据,这个字节代表地址的长度
        print(addr_len)
        dest_addr = client_socket.recv(addr_len).decode('utf-8') #接收地址对应长度的字节,得到目标域名信息
    dest_port = int.from_bytes(client_socket.recv(2), byteorder='big') #继续接收2个字节的长度,获取到目标端口信息
    remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    remote_socket.connect((dest_addr, dest_port)) #建立到远端的socker连接
    response = b"\x05\x00\x00\x01" + socket.inet_aton('0.0.0.0') + (0).to_bytes(2, byteorder='big') 
    # 连接成功后告知客户端已经连接成功,可以进行数据交互
    client_socket.sendall(response)
    def forward(src, dst):
        while True:
            data = src.recv(4096)
            if not data:
                break
            dst.sendall(data)
    threading.Thread(target=forward, args=(client_socket, remote_socket)).start()
    threading.Thread(target=forward, args=(remote_socket, client_socket)).start()
def main():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((listen_address, listen_port))
    server.listen(5)
    print(f"[*] Listening on {listen_address}:{listen_port}")
    while True:
        client_socket, addr = server.accept()
        # print(f"[*] Accepted connection from {addr[0]}:{addr[1]}")
        client_handler = threading.Thread(target=handle_client, args=(client_socket,))
        client_handler.start()
if __name__ == "__main__":
    listen_address,listen_port = sys.argv[1],int(sys.argv[2])
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *

X