python 3 изменить IP-адрес с помощью TOR + Privoxy не работает - PullRequest
0 голосов
/ 06 марта 2020

Я пытаюсь заставить работать следующий скрипт:

https://gist.github.com/KhepryQuixote/46cf4f3b999d7f658853

Я изменил скрипт, чтобы сделать его совместимым с моей версией Python (3.6); как показано ниже:

import stem
import stem.connection

import time
import urllib

from stem import Signal
from stem.control import Controller
from termcolor import cprint
import requests

# initialize some HTTP headers
# for later usage in URL requests
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers={'User-Agent':user_agent}

# initialize some
# holding variables
oldIP = "0.0.0.0"
newIP = "0.0.0.0"

# how many IP addresses
# through which to iterate?
nbrOfIpAddresses = 10

# seconds between
# IP address checks
secondsBetweenChecks = 2

# request a URL 
def request(url):
    # communicate with TOR via a local proxy (privoxy)
    def _set_urlproxy():
        proxy_support = urllib.request.ProxyHandler({"http" : "http://127.0.0.1:8118"})
        opener = urllib.request.build_opener(proxy_support)
        urllib.request.install_opener(opener)

    # request a URL
    # via the proxy
    _set_urlproxy()

    #response = requests.get(url, headers=headers, proxies=proxies)
    request=urllib.request.Request(url, None, headers=headers)
    response=urllib.request.urlopen(request).read()
    return response.decode('utf-8').strip()

# signal TOR for a new connection 
def renew_connection():
    with Controller.from_port(port=9051) as controller:
        controller.authenticate(password = 'my_password')
        #controller.signal(Signal.HUP)
        controller.signal(Signal.NEWNYM)

# cycle through
# the specified number
# of IP addresses via TOR 
for i in range(0, nbrOfIpAddresses):

    # if it's the first pass
    if newIP == "0.0.0.0":
        # renew the TOR connection
        renew_connection()

        # obtain the "new" IP address
        newIP = request("http://icanhazip.com/")

    # otherwise
    else:
        # remember the
        # "new" IP address
        # as the "old" IP address
        oldIP = newIP
        # refresh the TOR connection
        renew_connection()
        # obtain the "new" IP address
        newIP = request("http://icanhazip.com/")

    # zero the 
    # elapsed seconds    
    seconds = 0

    # loop until the "new" IP address
    # is different than the "old" IP address,
    # as it may take the TOR network some
    # time to effect a different IP address
    while oldIP == newIP:


        # sleep this thread
        # for the specified duration
        time.sleep(secondsBetweenChecks)
        # track the elapsed seconds
        seconds += secondsBetweenChecks
        # obtain the current IP address
        newIP = request("http://icanhazip.com/")
        # signal that the program is still awaiting a different IP address
        cprint("%d seconds elapsed awaiting a different IP address." % seconds, 'magenta', attrs=['bold'])
    # output the
    # new IP address
    print ("")
    cprint("newIP: %s" % newIP, 'cyan', attrs=['bold'])

Также я установил Tor и Privoxy на мою машину (Ubuntu 18) с помощью apt install. Ниже приведена моя конфигурация / etc / tor / torr c:

## The port on which Tor will listen for local connections from Tor
## controller applications, as documented in control-spec.txt.
ControlPort 9051
## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:B96CF050EAADEA746091CF998094E122F43A0A1EEC20E9D02FE5DB6A15
CookieAuthentication 1

, а вот моя конфигурация privoxy:

forward-socks5 / 127.0.0.1:9050 .

После запуска обеих служб я попытался выполнить приведенный выше скрипт. Тем не менее, в командной строке ничего не отображается, и после некоторого застревания появляется сообщение «сбой пересылки». Ниже приведено содержимое файла журнала privoxy:

2020-03-06 12:56:52.636 7f70109a90c0 Connect: Initialized 100 socket slots.
2020-03-06 12:56:52.636 7f70109a90c0 Connect: Waiting for the next client connection. Currently active threads: 0
2020-03-06 12:56:55.502 7f70109a90c0 Connect: Waiting for the next client connection. Currently active threads: 1
2020-03-06 12:56:55.502 7f700ee88700 Connect: Accepted connection from 127.0.0.1 on socket 5
2020-03-06 12:56:55.502 7f700ee88700 Received: from socket 5: GET http://icanhazip.com/ HTTP/1.1\x0d\x0aAccept-Encoding: identity\x0d\x0aHost: icanhazip.com\x0d\x0aUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7\x0d\x0aConnection: close\x0d\x0a\x0d\x0a
2020-03-06 12:56:55.502 7f700ee88700 Connect: Complete client request received.
2020-03-06 12:56:55.502 7f700ee88700 Request: icanhazip.com/
2020-03-06 12:56:55.502 7f700ee88700 Connect: to icanhazip.com
2020-03-06 12:56:55.502 7f700ee88700 Connect: Connected to 127.0.0.1[127.0.0.1]:9050.
2020-03-06 12:56:55.502 7f700ee88700 Writing: to socket 6: \x05\x01\x00
2020-03-06 12:56:55.502 7f700ee88700 Received: from socket 6: \x05\x00
2020-03-06 12:56:55.502 7f700ee88700 Writing: to socket 6: \x05\x01\x00\x03\x0dicanhazip.com\x00P
2020-03-06 12:57:38.687 7f70109a90c0 Connect: Waiting for the next client connection. Currently active threads: 2
2020-03-06 12:57:38.687 7f700e687700 Connect: Accepted connection from 127.0.0.1 on socket 7
2020-03-06 12:57:38.687 7f700e687700 Received: from socket 7: GET http://icanhazip.com/ HTTP/1.1\x0d\x0aAccept-Encoding: identity\x0d\x0aHost: icanhazip.com\x0d\x0aUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7\x0d\x0aConnection: close\x0d\x0a\x0d\x0a
2020-03-06 12:57:38.687 7f700e687700 Connect: Complete client request received.
2020-03-06 12:57:38.687 7f700e687700 Request: icanhazip.com/
2020-03-06 12:57:38.687 7f700e687700 Connect: to icanhazip.com
2020-03-06 12:57:38.687 7f700e687700 Connect: Connected to 127.0.0.1[127.0.0.1]:9050.
2020-03-06 12:57:38.687 7f700e687700 Writing: to socket 8: \x05\x01\x00
2020-03-06 12:57:38.687 7f700e687700 Received: from socket 8: \x05\x00
2020-03-06 12:57:38.687 7f700e687700 Writing: to socket 8: \x05\x01\x00\x03\x0dicanhazip.com\x00P
2020-03-06 12:58:55.141 7f700ee88700 Received: from socket 6: \x05\x06\x00\x01\x00\x00\x00\x00\x00\x00
2020-03-06 12:58:55.141 7f700ee88700 Connect: socks5_connect: SOCKS5 TTL expired
2020-03-06 12:58:55.143 7f700ee88700 Writing: to socket 5: HTTP/1.1 503 Forwarding failure\x0d\x0aContent-Length: 7068\x0d\x0aContent-Type: text/html\x0d\x0aCache-Control: no-cache\x0d\x0aDate: Fri, 06 Mar 2020 17:58:55 GMT\x0d\x0aLast-Modified: Wed, 08 Jun 1955 12:00:00 GMT\x0d\x0aExpires: Sat, 17 Jun 2000 12:00:00 GMT\x0d\x0aPragma: no-cache\x0d\x0aConnection: close\x0d\x0a\x0d\x0a
2020-03-06 12:58:55.143 7f700ee88700 Writing: to socket 5: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\x0a<html>\x0a\x0a<head>\x0a  <title>503 - Forwarding failure (Privoxy@localhost)</title>\x0a  <meta http-equiv="Content-Style-Type" content="text/css">\x0a  <meta http-equiv="Content-Script-Type" content="text/javascript">\x0a  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\x0a  <meta name="robots" content="noindex,nofollow">\x0a  <link rel="shortcut icon" href="http://config.privoxy.org/error-favicon.ico">\x0a  <style type="text/css">\x0a\x0a/*\x0a * CSS for Privoxy CGI and script output\x0a *\x0a * Id: cgi-style.css,v\x0a */\x0a\x0a/*\x0a * General rules: Font, Color, Headings, Margins, Links\x0a */\x0abody,td,th { font-family: arial, helvetica, helv, sans-serif; }\x0abody { background-color: #ffffff; color: #000000; }\x0a\x0ah1 { font-size: 140%; margin: 0px; }\x0ah2 { font-size: 120%; margin: 0px; }\x0ah3 { font-size: 110%; margin: 0px; }\x0a\x0ap,pre  { margin-left: 15px; }\x0ali { margin: 2px 15px; }\x0adl { margin: 2px 15px; }\x0a\x0aa:link    { color: #0000dd; text-decoration: none; }\x0aa:visited { color: #330099; text-decoration: none; }\x0aa:active  { color: #3333ff; text-decoration: none; }\x0a\x0a/*\x0a * Boxen as Table elements:\x0a */\x0atd.title   { border: solid black 1px; background-color: #dddddd; }\x0atd.box     { border: solid black 1px; background-color: #eeeeee; }\x0atd.info    { border: solid black 1px; background-color: #ccccff; }\x0atd.warning { border: solid black 1px; background-color: #ffdddd; }\x0a\x0a/*\x0a * Special Table Boxen: for nesting, naked container and for\x0a * the Status field in CGI Output:\x0a */\x0atd.wrapbox { border: solid black 1px; padding: 5px; }\x0atd.container { padding: 0px; }\x0atd.status  { border: solid black 1px; background-color: #ff0000; color: #ffffff; font-size: 300%; font-weight: bolder; }\x0a\x0a/*\x0a * Same Boxen as <div>s:\x0a */\x0adiv.title    { border: solid black 1px; background-color: #dddddd; margin: 20px; padding: 20px; }\x0adiv.box      { border: solid black 1px; background-color: #eeeeee; margin: 20px; padding: 20px; }\x0adiv.info     { border: solid black 1px; background-color: #ccccff; margin: 20px; padding: 20px; }\x0adiv.warning  { border: solid black 1px; background-color: #ffdddd; margin: 20px; padding: 20px; }\x0adiv.wrapbox  { border: solid black 1px;                            margin: 20px; padding:  5px; }\x0a\x0a\x0a/*\x0a * Bold definitions in <dl>s, grey BG for table headings, transparent (no-bordered) table\x0a */\x0adt { font-weight: bold; }\x0ath { background-color: #dddddd; }\x0atable.transparent { border-style: none}\x0a\x0a/*\x0a * Special purpose paragraphs: Small for page footers,\x0a * Important for quoting wrong or dangerous examples,\x0a * Whiteframed for the toggle?mini=y CGI\x0a */\x0ap.small { font-size: 10px; margin: 0px; }\x0ap.important { border: solid black 1px; background-color: #ffdddd; font-weight: bold; padding: 2px; }\x0ap.whiteframed { margin: 5px; padding: 5px; border: solid black 1px; text-align: center; background-color: #eeeeee; }\x0a\x0a/*\x0a * Links as buttons:\x0a */\x0a\x0atd.buttons {\x0a  padding: 2px;\x0a}\x0a\x0aa.cmd, td.indentbuttons a, td.buttons a {\x0a  white-space: nowrap;\x0a  width: auto;\x0a  padding: 2px;\x0a  background-color: #dddddd;\x0a  color:            #000000;\x0a  text-decoration: none;\x0a  border-top:    1px solid #ffffff;\x0a  border-left:   1px solid #ffffff;\x0a  border-bottom: 1px solid #000000;\x0a  border-right:  1px solid #000000;\x0a}\x0aa.cmd:hover, td.indentbuttons a:hover, td.buttons a:hover {\x0a  background-color: #eeeeee;\x0a}\x0aa.cmd:active, td.indentbuttons a:active, td.buttons a:active {\x0a  border-top:    1px solid #000000;\x0a  border-left:   1px solid #000000;\x0a  border-bottom: 1px solid #ffffff;\x0a  border-right:  1px solid #ffffff;\x0a}\x0a\x0a\x0a/*\x0a * Special red emphasis:\x0a */\x0aem.warning, strong.warning { color: #ff0000 }\x0a\x0a/*\x0a * In show-status we use tables directly behind headlines\x0a * and for some reason or another the headlines are set to\x0a * "margin:0" and leave the tables no air to breath.\x0a *\x0a * A proper fix would be to replace or remove the "margin:0",\x0a * but as this affects every cgi page we do it another time\x0a * and use this workaround until then.\x0a */\x0a.box table { margin-top: 1em; }\x0a\x0a/*\x0a * Let the URL and pattern input fields scale with the browser\x0a * width and try to prevent vertical scroll bars if the width\x0a * is less than 80 characters.\x0a */\x0ainput.url, input.pattern { width: 95%; }\x0a  </style>\x0a</head>\x0a\x0a<body>\x0a\x0a  <table summary="" cellpadding="20" cellspacing="10" border="0" width="100%">\x0a    <tr>\x0a      <td class="status">\x0a        503\x0a      </td>\x0a      <td class="title" style="width: 100%">\x0a\x0a        <h1>\x0a          This is <a href="... [too long, truncated]
2020-03-06 12:59:38.142 7f700e687700 Received: from socket 8: \x05\x06\x00\x01\x00\x00\x00\x00\x00\x00
2020-03-06 12:59:38.142 7f700e687700 Connect: socks5_connect: SOCKS5 TTL expired
2020-03-06 12:59:38.143 7f700e687700 Writing: to socket 7: HTTP/1.1 503 Forwarding failure\x0d\x0aContent-Length: 7068\x0d\x0aContent-Type: text/html\x0d\x0aCache-Control: no-cache\x0d\x0aDate: Fri, 06 Mar 2020 17:59:38 GMT\x0d\x0aLast-Modified: Wed, 08 Jun 1955 12:00:00 GMT\x0d\x0aExpires: Sat, 17 Jun 2000 12:00:00 GMT\x0d\x0aPragma: no-cache\x0d\x0aConnection: close\x0d\x0a\x0d\x0a
2020-03-06 12:59:38.143 7f700e687700 Writing: to socket 7: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\x0a<html>\x0a\x0a<head>\x0a  <title>503 - Forwarding failure (Privoxy@localhost)</title>\x0a  <meta http-equiv="Content-Style-Type" content="text/css">\x0a  <meta http-equiv="Content-Script-Type" content="text/javascript">\x0a  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\x0a  <meta name="robots" content="noindex,nofollow">\x0a  <link rel="shortcut icon" href="http://config.privoxy.org/error-favicon.ico">\x0a  <style type="text/css">\x0a\x0a/*\x0a * CSS for Privoxy CGI and script output\x0a *\x0a * Id: cgi-style.css,v\x0a */\x0a\x0a/*\x0a * General rules: Font, Color, Headings, Margins, Links\x0a */\x0abody,td,th { font-family: arial, helvetica, helv, sans-serif; }\x0abody { background-color: #ffffff; color: #000000; }\x0a\x0ah1 { font-size: 140%; margin: 0px; }\x0ah2 { font-size: 120%; margin: 0px; }\x0ah3 { font-size: 110%; margin: 0px; }\x0a\x0ap,pre  { margin-left: 15px; }\x0ali { margin: 2px 15px; }\x0adl { margin: 2px 15px; }\x0a\x0aa:link    { color: #0000dd; text-decoration: none; }\x0aa:visited { color: #330099; text-decoration: none; }\x0aa:active  { color: #3333ff; text-decoration: none; }\x0a\x0a/*\x0a * Boxen as Table elements:\x0a */\x0atd.title   { border: solid black 1px; background-color: #dddddd; }\x0atd.box     { border: solid black 1px; background-color: #eeeeee; }\x0atd.info    { border: solid black 1px; background-color: #ccccff; }\x0atd.warning { border: solid black 1px; background-color: #ffdddd; }\x0a\x0a/*\x0a * Special Table Boxen: for nesting, naked container and for\x0a * the Status field in CGI Output:\x0a */\x0atd.wrapbox { border: solid black 1px; padding: 5px; }\x0atd.container { padding: 0px; }\x0atd.status  { border: solid black 1px; background-color: #ff0000; color: #ffffff; font-size: 300%; font-weight: bolder; }\x0a\x0a/*\x0a * Same Boxen as <div>s:\x0a */\x0adiv.title    { border: solid black 1px; background-color: #dddddd; margin: 20px; padding: 20px; }\x0adiv.box      { border: solid black 1px; background-color: #eeeeee; margin: 20px; padding: 20px; }\x0adiv.info     { border: solid black 1px; background-color: #ccccff; margin: 20px; padding: 20px; }\x0adiv.warning  { border: solid black 1px; background-color: #ffdddd; margin: 20px; padding: 20px; }\x0adiv.wrapbox  { border: solid black 1px;                            margin: 20px; padding:  5px; }\x0a\x0a\x0a/*\x0a * Bold definitions in <dl>s, grey BG for table headings, transparent (no-bordered) table\x0a */\x0adt { font-weight: bold; }\x0ath { background-color: #dddddd; }\x0atable.transparent { border-style: none}\x0a\x0a/*\x0a * Special purpose paragraphs: Small for page footers,\x0a * Important for quoting wrong or dangerous examples,\x0a * Whiteframed for the toggle?mini=y CGI\x0a */\x0ap.small { font-size: 10px; margin: 0px; }\x0ap.important { border: solid black 1px; background-color: #ffdddd; font-weight: bold; padding: 2px; }\x0ap.whiteframed { margin: 5px; padding: 5px; border: solid black 1px; text-align: center; background-color: #eeeeee; }\x0a\x0a/*\x0a * Links as buttons:\x0a */\x0a\x0atd.buttons {\x0a  padding: 2px;\x0a}\x0a\x0aa.cmd, td.indentbuttons a, td.buttons a {\x0a  white-space: nowrap;\x0a  width: auto;\x0a  padding: 2px;\x0a  background-color: #dddddd;\x0a  color:            #000000;\x0a  text-decoration: none;\x0a  border-top:    1px solid #ffffff;\x0a  border-left:   1px solid #ffffff;\x0a  border-bottom: 1px solid #000000;\x0a  border-right:  1px solid #000000;\x0a}\x0aa.cmd:hover, td.indentbuttons a:hover, td.buttons a:hover {\x0a  background-color: #eeeeee;\x0a}\x0aa.cmd:active, td.indentbuttons a:active, td.buttons a:active {\x0a  border-top:    1px solid #000000;\x0a  border-left:   1px solid #000000;\x0a  border-bottom: 1px solid #ffffff;\x0a  border-right:  1px solid #ffffff;\x0a}\x0a\x0a\x0a/*\x0a * Special red emphasis:\x0a */\x0aem.warning, strong.warning { color: #ff0000 }\x0a\x0a/*\x0a * In show-status we use tables directly behind headlines\x0a * and for some reason or another the headlines are set to\x0a * "margin:0" and leave the tables no air to breath.\x0a *\x0a * A proper fix would be to replace or remove the "margin:0",\x0a * but as this affects every cgi page we do it another time\x0a * and use this workaround until then.\x0a */\x0a.box table { margin-top: 1em; }\x0a\x0a/*\x0a * Let the URL and pattern input fields scale with the browser\x0a * width and try to prevent vertical scroll bars if the width\x0a * is less than 80 characters.\x0a */\x0ainput.url, input.pattern { width: 95%; }\x0a  </style>\x0a</head>\x0a\x0a<body>\x0a\x0a  <table summary="" cellpadding="20" cellspacing="10" border="0" width="100%">\x0a    <tr>\x0a      <td class="status">\x0a        503\x0a      </td>\x0a      <td class="title" style="width: 100%">\x0a\x0a        <h1>\x0a          This is <a href="... [too long, truncated]

Кроме того, я также попытался удалить точку (.) Из конфигурации privoxy:

forward-socks5 / 127.0.0.1:9050

и скрипт запустился показывает результаты, но IP-адрес не меняется вообще.

Может кто-нибудь помочь мне решить проблему, пожалуйста? Спасибо.

...