Ошибка в использование requests socks5 с threading

Помогите понять в чем ошибка и как исправить, я как думаю что socks не может запускаться с разными ip в разных потоках. Как это можно исправить.

import requests
import sys
import time
from datetime import datetime,timedelta
from threading import Thread


class my_proxy():
    def manual_list(self):
        list_proxy = []
        list_proxy.append(['109.172.111.30', 'port', 'login', 'pass','port'])
        list_proxy.append(['149.126.232.99', 'port', 'login', 'pass','port'])
        list_proxy.append(['185.29.124.192', 'port', 'login', 'pass','port'])

        return list_proxy

c_my_proxy = my_proxy()
list_proxy = c_my_proxy.manual_list()

def fff(thread_number):
    s = requests.Session()
    proxies = dict(http="socks5://" + str(list_proxy[thread_number][2]) + ":" + str(
        list_proxy[thread_number][3]) + "@" + str(list_proxy[thread_number][0]) + ":" + str(
        list_proxy[thread_number][4]) + "",
                  https="socks5://" + str(list_proxy[thread_number][2]) + ":" + str(
                      list_proxy[thread_number][3]) + "@" + str(list_proxy[thread_number][0]) + ":" + str(
                      list_proxy[thread_number][4]) + "")
    print(thread_number, ' -- ', proxies)

    resp = s.get('http://icanhazip.com/',proxies=proxies)
    print(thread_number,' - - - -  ',resp.text)



for thread_number in range(1,10):
    if thread_number >=1:
        th = Thread(target=fff, args=(thread_number, ))
        th.start()
        time.sleep(5)

Первый поток отрабатывает запрос, после идет ошибка

1  --  {'http': 'socks5://login:[email protected]:port', 'https': 'socks5://login:[email protected]:port'}
1  - - - -   149.126.232.99

2  --  {'http': 'socks5://login:[email protected]:port', 'https': 'socks5://login:[email protected]:port'}
Exception in thread Thread-2:
Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 809, in connect
    negotiate(self, dest_addr, dest_port)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 443, in _negotiate_SOCKS5
    self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 533, in _SOCKS5_request
    raise SOCKS5Error("{:#04x}: {}".format(status, error))
socks.SOCKS5Error: 0x02: Connection not allowed by ruleset

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\contrib\socks.py", line 96, in _new_conn
    conn = socks.create_connection(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 209, in create_connection
    raise err
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 199, in create_connection
    sock.connect((remote_host, remote_port))
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 47, in wrapper
    return function(*args, **kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\socks.py", line 814, in connect
    raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: 0x02: Connection not allowed by ruleset

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connection.py", line 239, in request
    super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1285, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1331, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1280, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 1040, in _send_output
    self.send(msg)
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\http\client.py", line 980, in send
    self.connect()
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connection.py", line 205, in connect
    conn = self._new_conn()
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\contrib\socks.py", line 127, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.contrib.socks.SOCKSConnection object at 0x000001DB39B98D00>: Failed to establish a new connection: 0x02: Connection not allowed by ruleset

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\adapters.py", line 489, in send
    resp = conn.urlopen(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\connectionpool.py", line 787, in urlopen
    retries = retries.increment(
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\urllib3\util\retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: SOCKSHTTPConnectionPool(host='icanhazip.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSConnection object at 0x000001DB39B98D00>: Failed to establish a new connection: 0x02: Connection not allowed by ruleset'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\Users\Hitro\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "D:\pythonProject\dparsingsale\conn\test2.py", line 39, in fff
    resp = s.get('http://icanhazip.com/',proxies=proxies)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\sessions.py", line 600, in get
    return self.request("GET", url, **kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\sessions.py", line 587, in request
    resp = self.send(prep, **send_kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\sessions.py", line 701, in send
    r = adapter.send(request, **kwargs)
  File "D:\pythonProject\dparsingsale\venv\lib\site-packages\requests\adapters.py", line 565, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: SOCKSHTTPConnectionPool(host='icanhazip.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSConnection object at 0x000001DB39B98D00>: Failed to establish a new connection: 0x02: Connection not allowed by ruleset'))
Traceback (most recent call last):
  File "D:\pythonProject\dparsingsale\conn\test2.py", line 48, in <module>
    time.sleep(5)
KeyboardInterrupt

Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)

Ответы (1 шт):

Автор решения: Сергей Ш

Как пример.

from threading import Thread
import requests


def fff(thread_number, proxies):
    try:
        resp = requests.get('http://icanhazip.com/',proxies=proxies)
        txt = resp.text.strip()
    except Exception as ex:
        txt = ex

    print(thread_number,'  - -  ',txt)

list_proxy =[{'http': 'socks5://103.214.112.240:32323',
              'https': 'socks5://103.214.112.240:32323'},
             {'http': 'socks5://138.94.92.26:7497',
              'https': 'socks5://138.94.92.26:7497'},
             {'http': 'socks5://170.238.79.2:7497',
              'https': 'socks5://170.238.79.2:7497'}]
# login = 'IAmGroot'
# passw ="12345"
#
# list_proxy =[{'http': f'socks5://{login}:{passw}@149.126.232.99:1234',
#               'https': f'socks5://{login}:{passw}@149.126.232.99:1234'},
#              {'http': f'socks5://{login}:{passw}@149.126.232.99:8888',
#               'https': f'socks5://{login}:{passw}@149.126.232.99:8888' }
#              ]

for thread_number, proxy in enumerate(list_proxy):
    th = Thread(target=fff, args=(thread_number, proxy, ))
    th.start()

1   - -   138.94.92.26
0   - -   103.214.112.240
2   - -   170.238.79.2
→ Ссылка