Search code examples
pythonpython-requestssocks

How do I make a requesocks request with socks5 username and password?


I currently use this for my connection to a socks5 proxy and paramiko.

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,socks_hostname,socks_port, True, socks_username,socks_password)
paramiko.client.socket.socket = socks.socksocket
ssh = paramiko.SSHClient()

However, I was hoping to make some requests in python with requesocks and the same proxy settings for the paramiko and couldn't find anything talking about a username and password.

Additionally, all requests are done with a different socks connection each time, Global settings could get in the way of my other connections.

Any ideas on how this is done or if there is an alternative to this? My current implementation uses python requests very heavily so it would be nice to transition from there to requesocks so I don't have to refactor everything.

Note: How to make python Requests work via socks proxy doesn't work as it doesn't use the socks5 authentication.


Solution

  • You can use PySocks:

    pip install PySocks
    

    Then in your python file:

    import socket
    import socks
    import requests
    
    socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050, True, 'socks5_user','socks_pass')
    socket.socket = socks.socksocket
    print(requests.get('http://ifconfig.me/ip').text)
    

    It works for me. But I got another problem to use different socks5 proxy for different request sessions. If anyone has solution for this, please kindly contribute.