File: example_socks5.py

package info (click to toggle)
socksio 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 260 kB
  • sloc: python: 1,117; makefile: 12; sh: 12
file content (68 lines) | stat: -rw-r--r-- 2,012 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import socket

from socksio import socks5


def send_data(sock, data):
    print("Sending:", data)
    sock.sendall(data)


def receive_data(sock):
    data = sock.recv(1024)
    print("Received:", data)
    return data


def main():
    # Assuming a running SOCKS5 proxy running in localhost:1080
    sock = socket.create_connection(("localhost", 1080))
    conn = socks5.SOCKS5Connection()

    # The proxy may return any of these options
    request = socks5.SOCKS5AuthMethodsRequest(
        [
            socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED,
            socks5.SOCKS5AuthMethod.USERNAME_PASSWORD,
        ]
    )
    conn.send(request)
    send_data(sock, conn.data_to_send())
    data = receive_data(sock)
    event = conn.receive_data(data)
    print("Auth reply:", event)

    # If the proxy requires username/password you'll have to edit them below
    if event.method == socks5.SOCKS5AuthMethod.USERNAME_PASSWORD:
        request = socks5.SOCKS5UsernamePasswordRequest(b"socksio", b"socksio")
        conn.send(request)
        send_data(sock, conn.data_to_send())
        data = receive_data(sock)
        event = conn.receive_data(data)
        print("User/pass auth reply:", event)
        if not event.success:
            raise Exception("Invalid username/password")

    # Request to connect to google.com port 80
    request = socks5.SOCKS5CommandRequest.from_address(
        socks5.SOCKS5Command.CONNECT, ("google.com", 80)
    )
    conn.send(request)
    send_data(sock, conn.data_to_send())
    data = receive_data(sock)
    event = conn.receive_data(data)
    print("Request reply:", event)

    if event.reply_code != socks5.SOCKS5ReplyCode.SUCCEEDED:
        raise Exception(
            "Server could not connect to remote host: {}".format(event.reply_code)
        )

    # Send an HTTP request to the connected proxy
    sock.sendall(b"GET / HTTP/1.1\r\nhost: google.com\r\n\r\n")
    data = receive_data(sock)
    print("Response", data)


if __name__ == "__main__":
    main()