Лайфхаки

Маленькие, полезные хитрости

Как использовать прокси для перебора.. Общая теория

17.08.2022 в 08:15

Как использовать прокси для перебора.. Общая теория

Какими же они будут, эти новые прокси, и зачем они нужны? Давай рассмотрим основные проблемы, с которыми приходится сталкиваться при бруте через обычные прокси. Предположим, что у тебя есть приватный SOCKS-бот, и есть где взять загрузки. Перед тобой встанут следующие затруднения:

  1. Очень, очень мало интернет-юзеров имеют реальный IP – IPv4-адреса подходят к концу, провайдеры сажают абонентов за NAT, откуда бот, само собой, работать не будет. Теряем много денег;
  2. 99% гарантия, что не ты один будешь использовать свои прокси – в итоге они очень быстро сдохнут, и брут будет идти медленно.

«Ну, и что же делать?», – спросишь ты. Так вот, сегодня я поведаю тебе об абсолютно новой концепции брута. Как обычно работает брутфорс? Он коннектится к прокси (SOCKS4/5 или HTTP(s)), передает им информацию, получает ответ и анализирует его. В нашем случае все будет по-другому — прокси коннектятся к брутфорсу, он вместо целого пакета логина передает только пару uin;password, и получает в ответ всего один байт – так мы уменьшаем объем переданной информации, и, следовательно, увеличиваем скорость. Пакет для логина собирается уже самой проксей, ею же анализируется ответ. Все предельно просто.

Requests прокси. Rotating Proxies with Requests

Remember how we said some developers use more than one proxy? Well, now you can too!

Anytime you find yourself scraping from a webpage repeatedly, it's good practice to use more than one proxy, because there's a good chance your scraper will get blocked, meaning your IP address will get banned. The scraping cancel culture is real! So, to avoid being canceled, it's best to utilize rotating proxies. A rotating proxy is a proxy server that assigns a new IP address from the proxy pool for each connection.

To rotate IP addresses, you first need to have a pool of IPs available. You can use free proxies found on the internet or commercial solutions. In most cases, if your service relies on scraped data a free proxy will most likely not be enough.

How to Rotate IPs with Requests

In order to start rotating your IP addresses, you need a list of free proxies. In the case free proxies do fit your scrapping needs, here you can find a. Today you'll be writing a script that chooses and rotates through proxies.

    First import therequests,BeautifulSoup, andchoicelibraries.

    Next define a methodget_proxy()that will be responsible for retrieving IP addresses for you to use. In this method you will define yoururlas whatever proxy list resources you choose to use. After sending a request api call, convert the response into a Beautiful Soup object to make extraction easier. Use the html5lib parser library to parse the website’s HTML, as you would for a browser. Create aproxyvariable that useschoiceto randomly choose an IP address from the list of proxies generated bysoup. Within the map function, you can use alambdafunction to convert the HTML element into text for both retrieved IP addresses and port numbers.

    Create aproxy_requestmethod that takes in 3 arguments: therequest_type, theurl, and **kwargs . Inside this method, define your proxy dictionary as the proxy returned from theget_proxymethod. Similiar to before, you'll use the, passing in your arguments.

import requests ip_addresses = (request_type, url, kwargs): : : proxy random randint( , len(ip_addresses) ) proxies { : ip_addresses(proxy), : ip_addresses(proxy)} response requests get(request_type, url, proxies proxies, timeout , kwargs) print( proxy ) : print( ) response

You can now scrape and rotate all at once!

Proxy in python. Features

    Fast & Scalable

      Threadless executions using asyncio

      Made to handletens-of-thousandsconnections / sec

# On Macbook Pro 2019 / 2 .4 GHz 8 -Core Intel Core i9 / 32 GB RAM ❯ ./helper/benchmark.sh CONCURRENCY: 100 workers, TOTAL REQUESTS: 100000 req Summary: Success rate: 1.0000 Total: 2.5489 secs Slowest: 0.0443 secs Fastest: 0.0006 secs Average: 0.0025 secs Requests/sec: 39232.6572 Total data: 1.81 MiB Size/request: 19 B Size/sec: 727.95 KiB Response time histogram: 0.001 |■■■■■ 0.001 |■■■■■■■■■■■■■■■■■■■■■ 0.002 |■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 0.002 |■■■■■■■■■■■■■■■■■■■■■■ 0.003 |■■■■■■■■■■■■■■■■

Consultandto control number of CPU cores utilized.

Seefor more details and for how to run benchmarks locally.

Programmable

  • Customize proxy behavior using. Example:
      --plugins proxy.plugin.ProxyPoolPlugin
  • Enable builtin. Example:
      --enable-web-server --plugins proxy.plugin.WebServerPlugin
  • Enable builtin. Example:
      --enable-reverse-proxy --plugins proxy.plugin.ReverseProxyPlugin
  • Plugin API is currently in development phase . Expect breaking changes. Seeon how to ensure reliability across code changes.
  • Real-time Dashboard

    • Optionally, enable.
      • Use--enable-dashboard
      • Then, visithttp://localhost:8899/dashboard
    • proxy.pyat runtime
    • Extend dashboard frontend usingtypescriptbased plugins
    • Dashboard is currently in development phase Expect breaking changes.
    Категории: Общая теория