Этот пост можно понять только, если освоил сокеты. У меня это процесс как раз проходит (см. пост с видео про сокеты ), потому здесь дадим основные ссылки для самообучения. Сначала то, что я просмотрел (в порядке просмотра), потом неудачная попытка выполнить код из ролика.
Потом я перечитал Wikipedia и сделал вывод о том, что объект Socket в Windows имеет ограниченную поддержку, ... ииииии.... в любом случае нужно будет решать вопрос с анонимностью и proxy (при большом количестве запросов к сайтам они будут меня блокировать). И в роликах прямо говорится о том, что приличным людям надо использовать Linux...
Наверное, пришла пора переключится на создание инфраструктуры Linux... Так что оставим этот пост незавершенным, чтобы сделать загрузочную флешку ...
Потом я перечитал Wikipedia и сделал вывод о том, что объект Socket в Windows имеет ограниченную поддержку, ... ииииии.... в любом случае нужно будет решать вопрос с анонимностью и proxy (при большом количестве запросов к сайтам они будут меня блокировать). И в роликах прямо говорится о том, что приличным людям надо использовать Linux...
Наверное, пришла пора переключится на создание инфраструктуры Linux... Так что оставим этот пост незавершенным, чтобы сделать загрузочную флешку ...
- Суть понятия socket на Хабре Сокеты в Python для начинающих
- Вилео про Сокеты для Хакеров Запускаем свой локальный сервер и подключаемся к нему через сокет.
- Вилео про Сокеты для Хакеров-2 Перехватываем трафик (WireShark) и потрошим перехваченый объект.
- Видеоролик под эти м текстом
- Продолжение Видеоролика под эти м текстом
В процессе обучения я понял, что начинать надо с простого кода примеров для сокетов. Примеры нужно пробовать для своего конкретного релиза Python с официального сайта
Подготовил для этого отдельный пост. Но примеры из поста выполнить не удалось... Полагаю, что от того, что Windows имеет ограниченную поддержку этой библиотеки Wikipedia. Во всех роликах используется Linux...
Подготовил для этого отдельный пост. Но примеры из поста выполнить не удалось... Полагаю, что от того, что Windows имеет ограниченную поддержку этой библиотеки Wikipedia. Во всех роликах используется Linux...
С другой стороны, есть API TOR и информация о сервисах TOR, например, Tails, библиотеки Stem, Txtorcon Вот блог Tor
И вот ссылка, которая может повлиять на все планы stem.torproject.org... Этот сайт я бегло просмотрел, впечатление такое, что библиотека предназначена для волонтеров, чтобы управлять серверами, которые они предоставляют для системы TOR...
Эта тема интересна сама по себе, но здесь нам надо бы собрать (желательно) действующие примеры анонимного граббинга сайтов через Tor...
И вот ссылка, которая может повлиять на все планы stem.torproject.org... Этот сайт я бегло просмотрел, впечатление такое, что библиотека предназначена для волонтеров, чтобы управлять серверами, которые они предоставляют для системы TOR...
Эта тема интересна сама по себе, но здесь нам надо бы собрать (желательно) действующие примеры анонимного граббинга сайтов через Tor...
In []:
Поэтому будем здесь изучать видеоролик и использовать новую версию с GitHub, ниже
In [3]:
import socks
help(socks)
Help on module socks: NAME socks FILE c:\users\kiss\anaconda\lib\site-packages\socks.py DESCRIPTION SocksiPy - Python SOCKS module. Version 1.5.0 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. =============================================================================== Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge Modifications made by Anorov (https://github.com/Anorov) -Forked and renamed to PySocks -Fixed issue with HTTP proxy failure checking (same bug that was in the old ___recvall() method) -Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler, courtesy of e000 (https://github.com/e000): https://gist.github.com/869791#file_socksipyhandler.py -Re-styled code to make it readable -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc. -Improved exception handling and output -Removed irritating use of sequence indexes, replaced with tuple unpacked variables -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b" " -Other general fixes -Added clarification that the HTTP proxy connection method only supports CONNECT-style tunneling HTTP proxies -Various small bug fixes CLASSES exceptions.IOError(exceptions.EnvironmentError) ProxyError GeneralProxyError HTTPError ProxyConnectionError SOCKS4Error SOCKS5AuthError SOCKS5Error socket._socketobject(__builtin__.object) socksocket class GeneralProxyError(ProxyError) | Method resolution order: | GeneralProxyError | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods inherited from ProxyError: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from ProxyError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class HTTPError(ProxyError) | Method resolution order: | HTTPError | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods inherited from ProxyError: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from ProxyError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class ProxyConnectionError(ProxyError) | Method resolution order: | ProxyConnectionError | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods inherited from ProxyError: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from ProxyError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class ProxyError(exceptions.IOError) | socket_err contains original socket.error exception. | | Method resolution order: | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods defined here: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class SOCKS4Error(ProxyError) | Method resolution order: | SOCKS4Error | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods inherited from ProxyError: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from ProxyError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class SOCKS5AuthError(ProxyError) | Method resolution order: | SOCKS5AuthError | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods inherited from ProxyError: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from ProxyError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class SOCKS5Error(ProxyError) | Method resolution order: | SOCKS5Error | ProxyError | exceptions.IOError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Methods inherited from ProxyError: | | __init__(self, msg, socket_err=None) | | __str__(self) | | ---------------------------------------------------------------------- | Data descriptors inherited from ProxyError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.IOError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __reduce__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class socksocket(socket._socketobject) | socksocket([family[, type[, proto]]]) -> socket object | | Open a SOCKS enabled socket. The parameters are the same as | those of the standard socket init. In order for SOCKS to work, | you must specify family=AF_INET, type=SOCK_STREAM and proto=0. | | Method resolution order: | socksocket | socket._socketobject | __builtin__.object | | Methods defined here: | | __init__(self, family=2, type=1, proto=0, _sock=None) | | connect(self, dest_pair) | Connects to the specified destination through a proxy. | Uses the same API as socket's connect(). | To select the proxy server, use set_proxy(). | | dest_pair - 2-tuple of (IP/hostname, port). | | get_peername(self) | Returns the IP address and port number of the destination | machine (note: get_proxy_peername returns the proxy) | | get_proxy_peername(self) | Returns the IP and port number of the proxy. | | get_proxy_sockname(self) | Returns the bound IP address and port number at the proxy. | | getpeername = get_peername(self) | | getproxypeername = get_proxy_peername(self) | | getproxysockname = get_proxy_sockname(self) | | set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None) | set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) | Sets the proxy to be used. | | proxy_type - The type of the proxy to be used. Three types | are supported: PROXY_TYPE_SOCKS4 (including socks4a), | PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP | addr - The address of the server (IP or DNS). | port - The port of the server. Defaults to 1080 for SOCKS | servers and 8080 for HTTP proxy servers. | rdns - Should DNS queries be performed on the remote side | (rather than the local side). The default is True. | Note: This has no effect with SOCKS4 servers. | username - Username to authenticate with to the server. | The default is no authentication. | password - Password to authenticate with to the server. | Only relevant when username is also provided. | | setproxy = set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | default_proxy = None | | ---------------------------------------------------------------------- | Methods inherited from socket._socketobject: | | accept(self) | accept() -> (socket object, address info) | | Wait for an incoming connection. Return a new socket representing the | connection, and the address of the client. For IP sockets, the address | info is a pair (hostaddr, port). | | bind(...) | bind(address) | | Bind the socket to a local address. For IP sockets, the address is a | pair (host, port); the host must refer to the local host. For raw packet | sockets the address is a tuple (ifname, proto [,pkttype [,hatype]]) | | close(self, _closedsocket=<class 'socket._closedsocket'>, _delegate_methods=('recv', 'recvfrom', 'recv_into', 'recvfrom_into', 'send', 'sendto'), setattr=<built-in function setattr>) | close() | | Close the socket. It cannot be used after this call. | | connect_ex(...) | connect_ex(address) -> errno | | This is like connect(address), but returns an error code (the errno value) | instead of raising an exception when an error occurs. | | dup(self) | dup() -> socket object | | Return a new socket object connected to the same system resource. | | fileno(...) | fileno() -> integer | | Return the integer file descriptor of the socket. | | getsockname(...) | getsockname() -> address info | | Return the address of the local endpoint. For IP sockets, the address | info is a pair (hostaddr, port). | | getsockopt(...) | getsockopt(level, option[, buffersize]) -> value | | Get a socket option. See the Unix manual for level and option. | If a nonzero buffersize argument is given, the return value is a | string of that length; otherwise it is an integer. | | gettimeout(...) | gettimeout() -> timeout | | Returns the timeout in seconds (float) associated with socket | operations. A timeout of None indicates that timeouts on socket | operations are disabled. | | ioctl(...) | ioctl(cmd, option) -> long | | Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are | SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants. | SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval). | | listen(...) | listen(backlog) | | Enable a server to accept connections. The backlog argument must be at | least 0 (if it is lower, it is set to 0); it specifies the number of | unaccepted connections that the system will allow before refusing new | connections. | | makefile(self, mode='r', bufsize=-1) | makefile([mode[, bufsize]]) -> file object | | Return a regular file object corresponding to the socket. The mode | and bufsize arguments are as for the built-in open() function. | | sendall(...) | sendall(data[, flags]) | | Send a data string to the socket. For the optional flags | argument, see the Unix manual. This calls send() repeatedly | until all data is sent. If an error occurs, it's impossible | to tell how much data has been sent. | | setblocking(...) | setblocking(flag) | | Set the socket to blocking (flag is true) or non-blocking (false). | setblocking(True) is equivalent to settimeout(None); | setblocking(False) is equivalent to settimeout(0.0). | | setsockopt(...) | setsockopt(level, option, value) | | Set a socket option. See the Unix manual for level and option. | The value argument can either be an integer or a string. | | settimeout(...) | settimeout(timeout) | | Set a timeout on socket operations. 'timeout' can be a float, | giving in seconds, or None. Setting a timeout of None disables | the timeout feature and is equivalent to setblocking(1). | Setting a timeout of zero is the same as setblocking(0). | | shutdown(...) | shutdown(flag) | | Shut down the reading side of the socket (flag == SHUT_RD), the writing side | of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR). | | ---------------------------------------------------------------------- | Data descriptors inherited from socket._socketobject: | | __weakref__ | list of weak references to the object (if defined) | | family | the socket family | | proto | the socket protocol | | recv | | recv_into | | recvfrom | | recvfrom_into | | send | | sendto | | type | the socket type FUNCTIONS create_connection(dest_pair, proxy_type=None, proxy_addr=None, proxy_port=None, proxy_username=None, proxy_password=None, timeout=None) create_connection(dest_pair, **proxy_args) -> socket object Like socket.create_connection(), but connects to proxy before returning the socket object. dest_pair - 2-tuple of (IP/hostname, port). **proxy_args - Same args passed to socksocket.set_proxy(). timeout - Optional socket timeout value, in seconds. get_default_proxy() Returns the default proxy, set by set_default_proxy. getdefaultproxy = get_default_proxy() Returns the default proxy, set by set_default_proxy. set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None) set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. setdefaultproxy = set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None) set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. wrap_module(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using set_default_proxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. wrapmodule = wrap_module(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using set_default_proxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. DATA DEFAULT_PORTS = {1: 1080, 2: 1080, 3: 8080} HTTP = 3 PRINTABLE_PROXY_TYPES = {1: 'SOCKS4', 2: 'SOCKS5', 3: 'HTTP'} PROXY_TYPE_HTTP = 3 PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 SOCKS4 = 1 SOCKS4_ERRORS = {91: 'Request rejected or failed', 92: 'Request reject... SOCKS5 = 2 SOCKS5_ERRORS = {1: 'General SOCKS server failure', 2: 'Connection not... __version__ = '1.5.0' VERSION 1.5.0
Вот копии примеров с GitHub¶
In []:
#import socks
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default
# Or
s.set_proxy(socks.SOCKS4, "localhost", 4444)
# Or
s.set_proxy(socks.HTTP, "5.5.5.5", 8888)
# Can be treated identical to a regular socket object
s.connect(("www.test.com", 80))
s.sendall("GET / ...")
print s.recv(4096)
In [4]:
socks.socksocket?
Ниже код из видеороликов ("один в один" ...устарели ? )¶
In [7]:
# Beginning of code from video TOR With Python Tutorial #1
import socket
import socks
import httplib
In []:
socks.PROXY_TYPE_SOCKS5
In [19]:
def connectTor():
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1",9050,True)
socket.socket = socks.socksocket
In [23]:
def main():
connectTor()
print("Connected to Tor")
conn=httplib.HTTPConnection("ipython.org/")
conn.request("GET","/")
response=conn.getresponse()
print(response.read())
In [24]:
#if __name__=="__main__":
main()
# end of code from video TOR With Python Tutorial #1
--------------------------------------------------------------------------- gaierror Traceback (most recent call last) <ipython-input-24-d369400f2b47> in <module>() 1 #if __name__=="__main__": ----> 2 main() 3 <ipython-input-23-850c255d3d00> in main() 3 print("Connected to Tor") 4 conn=httplib.HTTPConnection("ipython.org/") ----> 5 conn.request("GET","/") 6 response=conn.getresponse() 7 print(response.read()) C:\Users\kiss\Anaconda\lib\httplib.pyc in request(self, method, url, body, headers) 971 def request(self, method, url, body=None, headers={}): 972 """Send a complete request to the server.""" --> 973 self._send_request(method, url, body, headers) 974 975 def _set_content_length(self, body): C:\Users\kiss\Anaconda\lib\httplib.pyc in _send_request(self, method, url, body, headers) 1005 for hdr, value in headers.iteritems(): 1006 self.putheader(hdr, value) -> 1007 self.endheaders(body) 1008 1009 def getresponse(self, buffering=False): C:\Users\kiss\Anaconda\lib\httplib.pyc in endheaders(self, message_body) 967 else: 968 raise CannotSendHeader() --> 969 self._send_output(message_body) 970 971 def request(self, method, url, body=None, headers={}): C:\Users\kiss\Anaconda\lib\httplib.pyc in _send_output(self, message_body) 827 msg += message_body 828 message_body = None --> 829 self.send(msg) 830 if message_body is not None: 831 #message_body was not a string (i.e. it is a file) and C:\Users\kiss\Anaconda\lib\httplib.pyc in send(self, data) 789 if self.sock is None: 790 if self.auto_open: --> 791 self.connect() 792 else: 793 raise NotConnected() C:\Users\kiss\Anaconda\lib\httplib.pyc in connect(self) 770 """Connect to the host and port specified in __init__.""" 771 self.sock = socket.create_connection((self.host,self.port), --> 772 self.timeout, self.source_address) 773 774 if self._tunnel_host: C:\Users\kiss\Anaconda\lib\socket.pyc in create_connection(address, timeout, source_address) 551 host, port = address 552 err = None --> 553 for res in getaddrinfo(host, port, 0, SOCK_STREAM): 554 af, socktype, proto, canonname, sa = res 555 sock = None gaierror: [Errno 11001] getaddrinfo failed
Connected to Tor
В видеороликах такие ошибки не появляются. Однако, я все делал в Windows. Статья в Википедии Wikipedia натолкнула на мысль о том, что объект Socket имеет ограничения в Windows... Поэтому, прежде, чем искать другие ошибки, попробуем этот код на Linuux...
Продолжение следует
Продолжение следует
Посты чуть ниже также могут вас заинтересовать
Комментариев нет:
Отправить комментарий