Python | 使用Socks5
1. TCP
注意:安装
pip install PySocks
import socks
# 创建socket
s: socks.socksocket = socks.socksocket()
# 设置代理l
(username, password, ip, port) = ('', '', '', 0)
s.set_proxy(socks.SOCKS5, addr=ip, port=port, username=username, password=password)
# 连接百度
s.connect(("www.baidu.com", 80))
# 使用TCP发送Get请求
s.sendall(
b'GET / HTTP/1.1\n\r' +
b'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\n\r' +
b'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0\n\r' +
b'\n\r')
# 读取GET响应结果
print(s.recv(4096).decode(encoding='UTF-8'))
2. HTTP
示例1
# 代理信息
(username, password, ip, port) = ('', '', '', '')
proxies = {'https': f'socks5://{username}:{password}@{ip}:{port}'}
res = requests.get("https://www.ip.cn/api/index?ip=&type=0", proxies=proxies)
print(res.text) # Output: {"rs":1,"code":0,"address":"美国 亚利桑那 凤凰城 ","ip":"50.3.62.2","isDomain":0}
示例2
import requests
# 更新代理信息
(username, password, ip, port) = ('', '', '', '')
proxies = {'https': f'socks5://{username}:{password}@{ip}:{port}'}
session = requests.Session()
session.proxies = proxies
resp = session.get('https://www.ip.cn/api/index?ip=&type=0')
print(resp.text) # Output: {"rs":1,"code":0,"address":"美国 亚利桑那 凤凰城 ","ip":"50.3.62.2","isDomain":0}
3. WebSocket
安装依赖
pip install websocket-client
注意
如果提示Python Socks is needed for SOCKS proxying but is not available
,执行安装pip3 install python-socks
issues
示例1
import websocket
if __name__ == '__main__':
websocket.enableTrace(True) # 开启调试追踪
ws: websocket.WebSocket = websocket.WebSocket()
url: str = "wss://echo-websocket.hoppscotch.io"
# direct
# ws.connect(url)
# http proxy
# ws.connect(url, http_proxy_host="192.168.2.81", http_proxy_port=2222, proxy_type="http")
# socks5 proxy
ws.connect(url, http_proxy_host="192.168.2.81", http_proxy_port=2222, proxy_type="socks5")
# recv data
code, data = ws.recv_data()
print(code, data)
# send data
ws.send('abc', websocket.ABNF.OPCODE_TEXT)
示例2
import websocket
from websocket import WebSocketApp
def on_message(ws_app: WebSocketApp, message):
print(f"message: {message}")
def on_error(error):
print(f"error: {error}")
def on_close():
print(f"on_close")
def on_ping(message):
print(f"on_ping: {message}")
def on_pong(message):
print(f"on_pong: {message}")
def on_open(obj):
print(f"on_open: {obj}")
if __name__ == '__main__':
websocket.enableTrace(True) # 开启调试追踪
ws: WebSocketApp = WebSocketApp(
"wss://echo-websocket.hoppscotch.io",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
# direct
# self.ws.run_forever()
# http proxy
# self.ws.run_forever(http_proxy_host="192.168.2.81", http_proxy_port=2222, proxy_type='http')
# socks5 proxy
ws.run_forever(http_proxy_host="192.168.2.81", http_proxy_port=2222, proxy_type="socks5")