- Notifications
You must be signed in to change notification settings - Fork265
A SOCKS proxy client and wrapper for Python.
License
Anorov/PySocks
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
PySocks lets you send traffic through SOCKS proxy servers. It is a modern fork ofSocksiPy with bug fixes and extra features.
Acts as a drop-in replacement to the socket module. Seamlessly configure SOCKS proxies for any socket object by callingsocket_object.set_proxy()
.
- SOCKS proxy client for Python 2.7 and 3.4+
- TCP supported, UDP mostly supported (issues may occur in some edge cases)
- HTTP proxy client included but not supported or recommended (you should use requests', or your HTTP client's, own HTTP proxy interface)
- urllib2 handler included, but not supported.
pip install
/setup.py install
will automatically install thesockshandler
module.
pip install pysocks
Or download the tarball /git clone
and...
python setup.py install
These will install both thesocks
andsockshandler
modules.
Alternatively, include justsocks.py
in your project.
We highly recommend using therequests library for proxying HTTP traffic with SOCKS or HTTP proxies. It uses PySocks under the hood.
requests.get(url,proxies={"http":"socks5://proxyhostname:9050","https":"socks5://proxyhostname:9050"})
PySocks has an option for HTTP proxies, but it only supports CONNECT-based HTTP proxies, and in general we recommend using your HTTP client's native proxy support (such as requests'proxies
keyword argument) rather than PySocks'.
If you absolutely must, you can use the urllib2 handler in sockshandler.py, but it's not supported (and won't work for non-CONNECT-based HTTP proxies, as stated above).
importsockss=socks.socksocket()# Same API as socket.socket in the standard libs.set_proxy(socks.SOCKS5,"localhost")# SOCKS4 and SOCKS5 use port 1080 by default# Ors.set_proxy(socks.SOCKS4,"localhost",4444)# Ors.set_proxy(socks.HTTP,"5.5.5.5",8888)# Can be treated like a regular socket objects.connect(("www.somesite.com",80))s.sendall("GET / HTTP/1.1 ...")print(s.recv(4096))
To monkeypatch the entire standard library with a single default proxy:
importurllib2importsocketimportsockssocks.set_default_proxy(socks.SOCKS5,"localhost")socket.socket=socks.socksocket
Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python.
Original SocksiPy README attached below, amended to reflect API changes.
SocksiPy
A Python SOCKS module.
(C) 2006 Dan-Haim. All rights reserved.
See LICENSE file for details.
WHAT IS A SOCKS PROXY?
A SOCKS proxy is a proxy server at the TCP level. In other words, it acts asa tunnel, relaying all traffic going through it without modifying it.SOCKS proxies can be used to relay traffic using any network protocol thatuses TCP.
WHAT IS SOCKSIPY?
This Python module allows you to create TCP connections through a SOCKSproxy without any special effort.It also supports relaying UDP packets with a SOCKS5 proxy.
PROXY COMPATIBILITY
SocksiPy is compatible with three different types of proxies:
- SOCKS Version 4 (SOCKS4), including the SOCKS4a extension.
- SOCKS Version 5 (SOCKS5).
- HTTP Proxies which support tunneling using the CONNECT method.
SYSTEM REQUIREMENTS
Being written in Python, SocksiPy can run on any platform that has a Pythoninterpreter and TCP/IP support.This module has been tested with Python 2.3 and should work with greater versionsjust as well.
Simply copy the file "socks.py" to your Python'slib/site-packages
directory,and you're ready to go. [Editor's note: it is better to usepython setup.py install
for PySocks]
First load the socks module with the command:
>>> import socks>>>
The socks module provides a class calledsocksocket
, which is the base to all of the module's functionality.
Thesocksocket
object has the same initialization parameters as the normal socketobject to ensure maximal compatibility, however it should be noted thatsocksocket
will only function with family beingAF_INET
andtype being eitherSOCK_STREAM
orSOCK_DGRAM
.Generally, it is best to initialize thesocksocket
object with no parameters
>>> s = socks.socksocket()>>>
Thesocksocket
object has an interface which is very similiar to socket's (in factthesocksocket
class is derived from socket) with a few extra methods.To select the proxy server you would like to use, use theset_proxy
method, whosesyntax is:
set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
Explanation of the parameters:
proxy_type
- The type of the proxy server. This can be one of three possiblechoices:PROXY_TYPE_SOCKS4
,PROXY_TYPE_SOCKS5
andPROXY_TYPE_HTTP
for SOCKS4,SOCKS5 and HTTP servers respectively.SOCKS4
,SOCKS5
, andHTTP
are all aliases, respectively.
addr
- The IP address or DNS name of the proxy server.
port
- The port of the proxy server. Defaults to 1080 for socks and 8080 for http.
rdns
- This is a boolean flag than modifies the behavior regarding DNS resolving.If it is set to True, DNS resolving will be preformed remotely, on the server.If it is set to False, DNS resolving will be preformed locally. Please note thatsetting this to True with SOCKS4 servers actually use an extension to the protocol,called SOCKS4a, which may not be supported on all servers (SOCKS5 and http serversalways support DNS). The default is True.
username
- For SOCKS5 servers, this allows simple username / password authenticationwith the server. For SOCKS4 servers, this parameter will be sent as the userid.This parameter is ignored if an HTTP server is being used. If it is not provided,authentication will not be used (servers may accept unauthenticated requests).
password
- This parameter is valid only for SOCKS5 servers and specifies therespective password for the username provided.
Example of usage:
>>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080>>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081)
After the set_proxy method has been called, simply call the connect method with thetraditional parameters to establish a connection through the proxy:
>>> s.connect(("www.sourceforge.net", 80))>>>
Connection will take a bit longer to allow negotiation with the proxy server.Please note that calling connect without callingset_proxy
earlier will connectwithout a proxy (just like a regular socket).
Errors: Any errors in the connection process will trigger exceptions. The exceptionmay either be generated by the underlying socket layer or may be custom moduleexceptions, whose details follow:
classProxyError
- This is a base exception class. It is not raised directly butrather all other exception classes raised by this module are derived from it.This allows an easy way to catch all proxy-related errors. It descends fromIOError
.
AllProxyError
exceptions have an attributesocket_err
, which will contain either acaughtsocket.error
exception, orNone
if there wasn't any.
classGeneralProxyError
- When thrown, it indicates a problem which does not fallinto another category.
Sent invalid data
- This error means that unexpected data has been received fromthe server. The most common reason is that the server specified as the proxy isnot really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong.Connection closed unexpectedly
- The proxy server unexpectedly closed the connection.This may indicate that the proxy server is experiencing network or software problems.Bad proxy type
- This will be raised if the type of the proxy supplied to theset_proxy function was not one ofSOCKS4
/SOCKS5
/HTTP
.Bad input
- This will be raised if theconnect()
method is called with bad inputparameters.
classSOCKS5AuthError
- This indicates that the connection through a SOCKS5 serverfailed due to an authentication problem.
Authentication is required
- This will happen if you use a SOCKS5 server whichrequires authentication without providing a username / password at all.All offered authentication methods were rejected
- This will happen if the proxyrequires a special authentication method which is not supported by this module.Unknown username or invalid password
- Self descriptive.
classSOCKS5Error
- This will be raised for SOCKS5 errors which are not related toauthentication.The parameter is a tuple containing a code, as given by the server,and a description of theerror. The possible errors, according to the RFC, are:
0x01
- General SOCKS server failure - If for any reason the proxy server is unable tofulfill your request (internal server error).0x02
- connection not allowed by ruleset - If the address you're trying to connect tois blacklisted on the server or requires authentication.0x03
- Network unreachable - The target could not be contacted. A router on the networkhad replied with a destination net unreachable error.0x04
- Host unreachable - The target could not be contacted. A router on the networkhad replied with a destination host unreachable error.0x05
- Connection refused - The target server has actively refused the connection(the requested port is closed).0x06
- TTL expired - The TTL value of the SYN packet from the proxy to the target serverhas expired. This usually means that there are network problems causing the packetto be caught in a router-to-router "ping-pong".0x07
- Command not supported - For instance if the server does not support UDP.0x08
- Address type not supported - The client has provided an invalid address type.When using this module, this error should not occur.
classSOCKS4Error
- This will be raised for SOCKS4 errors. The parameter is a tuplecontaining a code and a description of the error, as given by the server. Thepossible error, according to the specification are:
0x5B
- Request rejected or failed - Will be raised in the event of an failure for anyreason other then the two mentioned next.0x5C
- request rejected because SOCKS server cannot connect to identd on the client -The Socks server had tried an ident lookup on your computer and has failed. In thiscase you should run an identd server and/or configure your firewall to allow incomingconnections to local port 113 from the remote server.0x5D
- request rejected because the client program and identd report different user-ids -The Socks server had performed an ident lookup on your computer and has received adifferent userid than the one you have provided. Change your userid (through theusername parameter of the set_proxy method) to match and try again.
classHTTPError
- This will be raised for HTTP errors. The message will containthe HTTP status code and provided error message.
After establishing the connection, the object behaves like a standard socket.
Methods likemakefile()
andsettimeout()
should behave just like regular sockets.Call theclose()
method to close the connection.
In addition to thesocksocket
class, an additional function worth mentioning is theset_default_proxy
function. The parameters are the same as theset_proxy
method.This function will set default proxy settings for newly createdsocksocket
objects,in which the proxy settings haven't been changed via theset_proxy
method.This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy,by overriding the socket object.For example:
>>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com")>>> socket.socket = socks.socksocket>>> urllib.urlopen("http://www.sourceforge.net/")
Please open a GitHub issue athttps://github.com/Anorov/PySocks
About
A SOCKS proxy client and wrapper for Python.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.