Skip to content

Commit

Permalink
Make sockshandler 2/3 compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
Anorov committed Mar 28, 2015
1 parent b756909 commit 86b9a47
Showing 1 changed file with 31 additions and 12 deletions.
43 changes: 31 additions & 12 deletions sockshandler.py
@@ -1,16 +1,28 @@
#!/usr/bin/env python
"""
SocksiPy + urllib2 handler
version: 0.2
version: 0.3
author: e<e@tr0ll.in>
This module provides a Handler which you can use with urllib2 to allow it to tunnel your connection through a socks.sockssocket socket, with out monkey patching the original socket...
"""
import urllib2
import httplib
import socks
import ssl

try:
import urllib2
import httplib
except ImportError: # Python 3
import urllib.request as urllib2
import http.client as httplib

import socks # $ pip install PySocks

def merge_dict(a, b):
d = a.copy()
d.update(b)
return d

class SocksiPyConnection(httplib.HTTPConnection):
def __init__(self, proxytype, proxyaddr, proxyport=None, rdns=True, username=None, password=None, *args, **kwargs):
self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password)
Expand All @@ -35,26 +47,33 @@ def connect(self):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)

class SocksiPyHandler(urllib2.HTTPHandler, urllib2.HTTPSHandler):
def __init__(self, *args, **kwargs):
self.args = args
self.kw = kwargs
urllib2.HTTPHandler.__init__(self)

def http_open(self, req):
def build(host, port=None, strict=None, timeout=0):
conn = SocksiPyConnection(*self.args, host=host, port=port, strict=strict, timeout=timeout, **self.kw)
def build(host, port=None, timeout=0, **kwargs):
kw = merge_dict(self.kw, kwargs)
conn = SocksiPyConnection(*self.args, host=host, port=port, timeout=timeout, **kw)
return conn
return self.do_open(build, req)

def https_open(self, req):
def build(host, port=None, strict=None, timeout=0):
conn = SocksiPyConnectionS(*self.args, host=host, port=port, strict=strict, timeout=timeout, **self.kw)
def build(host, port=None, timeout=0, **kwargs):
kw = merge_dict(self.kw, kwargs)
conn = SocksiPyConnectionS(*self.args, host=host, port=port, timeout=timeout, **kw)
return conn
return self.do_open(build, req)

if __name__ == "__main__":
opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "localhost", 9050))
print "HTTP:", opener.open("http://httpbin.org/ip").read()
print "HTTPS:", opener.open("https://httpbin.org/ip").read()
import sys
try:
port = int(sys.argv[1])
except (ValueError, IndexError):
port = 9050
opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "localhost", port))
print("HTTP: " + opener.open("http://httpbin.org/ip").read().decode())
print("HTTPS: " + opener.open("https://httpbin.org/ip").read().decode())

0 comments on commit 86b9a47

Please sign in to comment.