我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socks.socksocket()。
def __init__(self, roomId): proxyIp = "216.189.158.147" proxyPort = 52940 # socks ?????? # self.sock = socks.socksocket() # self.sock.set_proxy(socks.SOCKS5, proxyIp, proxyPort) self.mongo_clent = MongoDBClient.MongoDBClient('douyu') # socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxyIp, proxyPort) socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, proxyIp, proxyPort) socket.socket = socks.socksocket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.codeLocalToServer = 689 self.serverToLocal = 690 self.gid = -9999 self.roomId = roomId self.server = {} self.log("??? :" + str(self.roomId))
def connect_to_server(self): self.channels_to_join = copy.deepcopy(self.irc_channels) glados.log('Connecting to: {}:{}'.format(self.host, self.port)) try: self.socket = socks.socksocket() if not self.irc_settings.setdefault('proxy host', 'none') == 'none' \ and not self.irc_settings.setdefault('proxy port', 'none') == 'none': self.socket.setproxy(socks.PROXY_TYPE_SOCKS5, self.irc_settings['proxy host'], int(self.irc_settings['proxy port']), True) self.socket.connect((self.host, self.port)) self.send_raw_message('USER {0} {0} {0} :{0}\n'.format(self.botnick)) if not self.irc_settings.setdefault('password', 'none') == '': #self.send_raw_message('PRIVMSG NickServ :IDENTIFY {} {}\n'.format(self.botnick, self.irc_settings['password'])) self.send_raw_message('PASS {}\n'.format(self.irc_settings['password'])) self.send_raw_message('NICK {}\n'.format(self.botnick)) self.state = self.STATE_TRY_JOIN except Exception as e: glados.log('Exception caught: {}'.format(e)) exc_info = sys.exc_info() traceback.print_exception(*exc_info)
def run(self): # la funzione che da' le istruzioni ai vari threads data = random._urandom(1024) # data per il pacchetto random p = bytes(IP(dst=str(url2))/TCP(sport=RandShort(), dport=int(port))/data) # costruzione pacchetto tcp + data current = x # per dare l'id al thread if current < len(proxies): # se l'id del thread si puo' associare ad un proxy, usa quel proxy proxy = proxies[current].strip().split(':') else: # altrimenti lo prende a random proxy = random.choice(proxies).strip().split(":") go.wait() # aspetta che tutti i proxy siano pronti while True: try: socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, str(proxy[0]), int(proxy[1]), True) # comando per il proxying HTTP s = socks.socksocket() # creazione socket s.connect((str(url2),int(port))) # si connette s.send(p) # ed invia print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # print req + counter except: # se si verifica un errore s.close() # chiude il thread e ricomincia
def run(self): # la funzione che da' le istruzioni ai vari threads data = random._urandom(1024) # data per il pacchetto random p = bytes(IP(dst=str(url2))/UDP(dport=int(port))/data) # crea pacchetto udp classico + data current = x # per dare l'id al thread if current < len(proxies): # se l'id del thread si puo' associare ad un proxy, usa quel proxy proxy = proxies[current].strip().split(':') else: # altrimenti lo prende a random proxy = random.choice(proxies).strip().split(":") go.wait() # aspetta che threads sono pronti while True: try: socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, str(proxy[0]), int(proxy[1]), True) # comando per il proxying HTTP s = socks.socksocket() # creazione socket s.connect((str(url2),int(port))) # connessione s.send(p) # invio print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # print req + counter except: # se qualcosa va storto s.close() # chiude il socket
def init_proxy(proxy): res = urlparse(proxy) use_proxy = True if res.scheme == 'socks4': mode = socks.SOCKS4 elif res.scheme == 'socks5': mode = socks.SOCKS5 elif res.scheme == 'http': mode = socks.HTTP else: use_proxy = False ksprint.print_error('Unknown proxy "%s", starting without proxy...' % proxy) if use_proxy: socks.set_default_proxy(mode, res.netloc.split(':')[0], int(res.netloc.split(':')[1])) soc.socket = socks.socksocket ksprint.print_success('[*] Proxy "%s" using' % proxy)
def _do_read(self, query, raw=False): # send query to server, return JSON rethinker = doublethink.Rethinker(db="trough_configuration", servers=self.rethinkdb) healthy_databases = list(rethinker.table('services').get_all(self.database, index='segment').run()) healthy_databases = [db for db in healthy_databases if db['role'] == 'trough-read' and (rethinker.now().run() - db['last_heartbeat']).seconds < db['ttl']] try: assert len(healthy_databases) > 0 except: raise Exception('No healthy node found for segment %s' % self.database) url = urlparse(healthy_databases[0].get('url')) if self.proxy: conn = HTTPConnection(self.proxy, self.proxy_port) conn.set_tunnel(url.netloc, url.port) conn.sock = socks.socksocket() conn.sock.set_proxy(self.proxy_type, self.proxy, self.proxy_port) conn.sock.connect((url.netloc.split(":")[0], url.port)) else: conn = HTTPConnection(url.netloc) request_path = "%s?%s" % (url.path, url.query) conn.request("POST", request_path, query) response = conn.getresponse() results = json.loads(response.read()) self._last_results = results
def __init__(self, ipv6=False, ssl=False, proxy=False, proxy_host=None, proxy_port=None, proxy_type=None): self.attachments = [] if proxy: self.attachments.append("proxy") self.socket = socks.socksocket() self.socket.set_proxy(proxy_type, proxy_host, proxy_port) elif ipv6: self.attachments.append("IPv6") self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if ssl and not proxy: self.attachments.append("SSL") self.socket = _ssl.wrap_socket(self.socket) self.connect = self.socket.connect self.close = self.socket.close self.connected = False
def URL(url): socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050) socket.socket = socks.socksocket socket.create_connection = create_connection file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() print ""
def _update(__version__, __code_name__, language, socks_proxy): try: if socks_proxy is not None: socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4 socks_proxy = socks_proxy.rsplit('://')[1] socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1])) socket.socket = socks.socksocket socket.getaddrinfo = getaddrinfo data = requests.get(url, headers={"User-Agent": "OWASP Nettacker"}).content if version() is 3: data = data.decode("utf-8") if __version__ + ' ' + __code_name__ == data.rsplit('\n')[0]: info(messages(language, 103)) else: warn(messages(language, 101)) warn(messages(language, 85)) except: warn(messages(language, 102)) return
def _check(__version__, __code_name__, language, socks_proxy): try: if socks_proxy is not None: socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4 socks_proxy = socks_proxy.rsplit('://')[1] socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1])) socket.socket = socks.socksocket socket.getaddrinfo = getaddrinfo data = requests.get(url, headers={"User-Agent": "OWASP Nettacker"}).content if version() is 3: data = data.decode("utf-8") if __version__ + ' ' + __code_name__ == data.rsplit('\n')[0]: info(messages(language, 103)) else: warn(messages(language, 101)) except: warn(messages(language, 102)) return
def __connect_to_port(port, timeout_sec, target, retries, language, num, total, time_sleep, ports_tmp_filename, socks_proxy): exit = 0 if socks_proxy is not None: socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4 socks_proxy = socks_proxy.rsplit('://')[1] socks.set_default_proxy(socks.SOCKS5, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1])) socket.socket = socks.socksocket socket.getaddrinfo = getaddrinfo while 1: try: if timeout_sec is not None: my_ftp = FTP(timeout=timeout_sec) else: my_ftp = FTP() my_ftp.connect(target, int(port)) exit = 0 break except: exit += 1 if exit is retries: error(messages(language, 68).format(target, port, str(num), str(total))) try: f = open(ports_tmp_filename, 'a') f.write(str(port) + '\n') f.close() except: pass break time.sleep(time_sleep)
def test(target, retries, timeout_sec, user_agent, http_method, socks_proxy): if socks_proxy is not None: socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4 socks_proxy = socks_proxy.rsplit('://')[1] socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1])) socket.socket = socks.socksocket socket.getaddrinfo = getaddrinfo n = 0 while 1: try: if http_method == "GET": r = requests.get(target, timeout=timeout_sec, headers=user_agent, verify=True) elif http_method == "HEAD": r = requests.head(target, timeout=timeout_sec, headers=user_agent, verify=True) return 0 except: n += 1 if n is retries: return 1
def _recreate_socket(self): if self._proxy is None: self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: import socks self._socket = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) if type(self._proxy) is dict: self._socket.set_proxy(**self._proxy) else: # tuple, list, etc. self._socket.set_proxy(*self._proxy)
def __init__(self, host, port, tor): Thread.__init__(self) self.host = host self.port = port self.socks = socks.socksocket() self.tor = tor self.running = True
def run(self): while self.running: while self.running: try: if self.tor: self.socks.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050) self.socks.connect((self.host, self.port)) print term.BOL+term.UP+term.CLEAR_EOL+"Connected to host..."+ term.NORMAL break except Exception, e: if e.args[0] == 106 or e.args[0] == 60: break print term.BOL+term.UP+term.CLEAR_EOL+"Error connecting to host..."+ term.NORMAL time.sleep(1) continue while self.running: try: self._send_http_post() except Exception, e: if e.args[0] == 32 or e.args[0] == 104: print term.BOL+term.UP+term.CLEAR_EOL+"Thread broken, restarting..."+ term.NORMAL self.socks = socks.socksocket() break time.sleep(0.1) pass
def _recreate_socket(self, mode): if self.proxy is None: self._socket = socket.socket(mode, socket.SOCK_STREAM) else: import socks self._socket = socks.socksocket(mode, socket.SOCK_STREAM) if type(self.proxy) is dict: self._socket.set_proxy(**self.proxy) else: # tuple, list, etc. self._socket.set_proxy(*self.proxy) self._socket.settimeout(self.timeout)
def connectTor(): try: SOCKS_PORT = 9050 # Set socks proxy and wrap the urllib module socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_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")
def _simple_check_worker(): global _checking_lock, _checking_num, network_stat, last_check_time time_now = time.time() if config.PROXY_ENABLE: socket.socket = socks.socksocket xlog.debug("patch socks") _checking_lock.acquire() _checking_num += 1 _checking_lock.release() network_ok = False for host in ["www.microsoft.com", "www.apple.com", "code.jquery.com", "cdn.bootcss.com", "cdnjs.cloudflare.com"]: if _check_one_host(host): network_ok = True break if network_ok: last_check_time = time.time() report_network_ok() xlog.debug("network is ok, cost:%d ms", 1000 * (time.time() - time_now)) else: xlog.warn("network fail") network_stat = "Fail" last_check_time = time.time() _checking_lock.acquire() _checking_num -= 1 _checking_lock.release() if config.PROXY_ENABLE: socket.socket = default_socket xlog.debug("restore socket")
def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError( 'Proxy support missing but proxy use was requested!') msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if self.proxy_info and self.proxy_info.isgood(): self.sock = socks.socksocket(af, socktype, proto) # HACK: amorton enabled TCP_NODELAY on socket self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.sock.setproxy(*self.proxy_info.astuple()) else: self.sock = socket.socket(af, socktype, proto) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Different from httplib: support timeouts. if has_timeout(self.timeout): self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg
def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if self.proxy_info and self.proxy_info.isgood(): self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy(*self.proxy_info.astuple()) else: self.sock = socket.socket(af, socktype, proto) # Different from httplib: support timeouts. if self.timeout is not None: self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg
def __init__(self, room_id): threading.Thread.__init__(self) proxyIp = "116.255.153.137" proxyPort = 8082 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxyIp, proxyPort) # socket.socket = socks.socksocket self.mongo_clent = MongoDBClient.MongoDBClient('douyu') self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.codeLocalToServer = 689 self.serverToLocal = 690 self.gid = -9999 self.roomId = room_id self.server = {} self.log("??? :" + str(self.roomId))
def __init__(self): proxyIp = "116.255.153.137" proxyPort = 8082 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxyIp, proxyPort) # socket.socket = socks.socksocket self.mongo_clent = MongoDBClient.MongoDBClient('douyu') self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.codeLocalToServer = 689 self.serverToLocal = 690 self.gid = -9999 self.rid = 16789 self.server = {}
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 # ????????
def _connect(self): """??????whois?? ???socks.py (ver 1.5.7)""" # whois???ip???ip global _proxy_socks self.tcpCliSock = socks.socksocket() # ??socket?? self.tcpCliSock.settimeout(TIMEOUT) # ?????? data_result = "" try: self.tcpCliSock.connect((self.whois_srv, 43)) # ??whois??? self.tcpCliSock.send(self.request_data + '\r\n') # ???? except Exception as e: # Exception??socks.py ?????? if str(e).find("timed out") != -1 or \ str(e).find("TTL expired") != -1: # ???? self.tcpCliSock.close() return "ERROR -1" elif str(e).find("Temporary failure in name resolution") != -1 or \ str(e).find("cannot connect to identd on the client") != -1 or \ str(e).find("unreachable") != -1: self.tcpCliSock.close() return "ERROR -2" else: self.tcpCliSock.close() return "ERROR OTHER" # ???? while True: try: data_rcv = self.tcpCliSock.recv(1024) # ?????? except: self.tcpCliSock.close() return "ERROR -3" if not len(data_rcv): self.tcpCliSock.close() return data_result # ?????? data_result = data_result + data_rcv # ????????
def __init__(self, context, database): self.database = database self.sock = socks.socksocket() self.sock.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
def run(self): # la funzione che da' le istruzioni ai vari threads data = random._urandom(1024) # data per il pacchetto random p = bytes(IP(dst=str(url2))/TCP(sport=RandShort(), dport=int(port))/data) # costruzione pacchetto tcp + data current = x # per dare l'id al thread if current < len(proxies): # se l'id del thread si puo' associare ad un proxy, usa quel proxy proxy = proxies[current].strip().split(':') else: # altrimenti lo prende a random proxy = random.choice(proxies).strip().split(":") go.wait() # aspetta che threads siano pronti while True: try: socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, str(proxy[0]), int(proxy[1]), True) # comando per il proxying via SOCKS s = socks.socksocket() # creazione socket s.connect((str(url2),int(port))) # si connette s.send(p) # ed invia print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # print req + counter except: # se si verifica un errore s.close() # intanto chiude il precedente socket non funzionante try: socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, str(proxy[0]), int(proxy[1]), True) # poi prova ad utilizzare SOCKS4, magari e' questo il problema dell'errore s = socks.socksocket() # creazione socket s.connect((str(url2),int(port))) # connessione s.send(p) # invio print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # print req + counter except: # se nemmeno questo funge, allora il sock e' down print ("Sock down. Retrying request. @", self.counter) s.close() # chiude il socket e ricomincia ciclo
def run(self): # la funzione che da' le istruzioni ai vari threads data = random._urandom(1024) # data per il pacchetto random p = bytes(IP(dst=str(url2))/UDP(dport=int(port))/data) # crea pacchetto udp classico + data current = x # per dare l'id al thread if current < len(proxies): # se l'id del thread si puo' associare ad un proxy, usa quel proxy proxy = proxies[current].strip().split(':') else: # altrimenti lo prende a random proxy = random.choice(proxies).strip().split(":") go.wait() # aspetta che threads siano pronti while True: try: socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, str(proxy[0]), int(proxy[1]), True) # comando per il proxying con SOCKS s = socks.socksocket() # creazione socket s.connect((str(url2),int(port))) # connessione s.send(p) # invio print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # req + counter except: # se qualcosa va storto questo except chiude il socket e si collega al try sotto s.close() # intanto chiude il precedente socket non funzionante try: socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, str(proxy[0]), int(proxy[1]), True) # poi prova ad utilizzare SOCKS4, magari e' questo il problema dell'errore s = socks.socksocket() # creazione socket s.connect((str(url2),int(port))) # connessione s.send(p) # invio print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # req + counter except: # se nemmeno questo funge, allora il sock e' down print ("Sock down. Retrying request. @", self.counter) s.close() # chiude il socket e ricomincia ciclo
def run(self): # la funzione che da' le istruzioni ai vari threads useragent = "User-Agent: " + random.choice(useragents) + "\r\n" # scelta proxy a caso accept = random.choice(acceptall) # scelta accept a caso request = get_host + useragent + accept + connection + "\r\n" # composizione final request current = x # per dare l'id al thread if current < len(proxies): # se l'id del thread si puo' associare ad un proxy, usa quel proxy proxy = proxies[current].strip().split(':') else: # altrimenti lo prende a random proxy = random.choice(proxies).strip().split(":") go.wait() # aspetta che threads siano pronti while True: try: socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, str(proxy[0]), int(proxy[1]), True) # comando per proxarci con i socks s = socks.socksocket() # creazione socket con pysocks s.connect((str(url2), int(urlport))) # connessione s.send (str.encode(request)) # invio print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # print req + counter except: # se qualcosa va storto questo except chiude il socket e si collega al try sotto s.close() # chiude socket try: # il try prova a vedere se l'errore e' causato dalla tipologia di socks errata, infatti prova con SOCKS4 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, str(proxy[0]), int(proxy[1]), True) # prova con SOCKS4 s = socks.socksocket() # creazione nuovo socket s.connect((str(url2), int(urlport))) # connessione s.send (str.encode(request)) # invio print ("Request sent from " + str(proxy[0]+":"+proxy[1]) + " @", self.counter) # print req + counter except: print ("Sock down. Retrying request. @", self.counter) s.close() # se nemmeno con quel try si e' riuscito a inviare niente, allora il sock e' down e chiude il socket.
def get_recv_info(domain, whois_addr, tcpCliSock): # global _ip, _port, _mode HOST = whois_addr data_result = "" PORT = 43 # ?? BUFSIZ = 1024 # ???????? ADDR = (HOST, PORT) EOF = "\r\n" data_send = domain + EOF socks.setdefaultproxy(proxytype = _mode, addr = _ip, port = _port) socket.socket = socks.socksocket try: tcpCliSock.connect(ADDR) tcpCliSock.send(data_send) except socket.error, e: return # if str(e).find("time 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 = tcpCliSock.recv(BUFSIZ) except socket.error, e: return if not len(data_rcv): return data_result # ?????? data_result = data_result + data_rcv # ????????
def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if self.proxy_info and self.proxy_info.isgood(): self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy(*self.proxy_info.astuple()) else: self.sock = socket.socket(af, socktype, proto) # Different from httplib: support timeouts. if has_timeout(self.timeout): self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg
def connect(self): "Connect to a host on a given (SSL) port." if self.proxy_info and self.proxy_info.isgood(): sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) sock.setproxy(*self.proxy_info.astuple()) else: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if has_timeout(self.timeout): sock.settimeout(self.timeout) sock.connect((self.host, self.port)) self.sock =_ssl_wrap_socket(sock, self.key_file, self.cert_file)
def connect( self ): self.sock = socks.socksocket() self.sock.setproxy( *self.proxyargs ) if isinstance( self.timeout, float ): self.sock.settimeout( self.timeout ) self.sock.connect(( self.host, self.port ))
def create_connection(address, timeout=None, source_address=None): sock = socks.socksocket() sock.connect(address) return sock
def disable(cls): cls._is_enabled = False socket.socket = old_socket socket.SocketType = old_SocketType socket._socketobject = old_socket socket.create_connection = old_create_connection socket.gethostname = old_gethostname socket.gethostbyname = old_gethostbyname socket.getaddrinfo = old_getaddrinfo socket.__dict__['socket'] = old_socket socket.__dict__['_socketobject'] = old_socket socket.__dict__['SocketType'] = old_SocketType socket.__dict__['create_connection'] = old_create_connection socket.__dict__['gethostname'] = old_gethostname socket.__dict__['gethostbyname'] = old_gethostbyname socket.__dict__['getaddrinfo'] = old_getaddrinfo if socks: socks.socksocket = old_socksocket socks.__dict__['socksocket'] = old_socksocket if ssl: ssl.wrap_socket = old_ssl_wrap_socket ssl.SSLSocket = old_sslsocket ssl.__dict__['wrap_socket'] = old_ssl_wrap_socket ssl.__dict__['SSLSocket'] = old_sslsocket if not PY3: ssl.sslwrap_simple = old_sslwrap_simple ssl.__dict__['sslwrap_simple'] = old_sslwrap_simple if pyopenssl_override: # Replace PyOpenSSL Monkeypatching inject_into_urllib3()
def _check_worker(): global _checking_lock, _checking_num, network_stat, last_check_time time_now = time.time() if config.PROXY_ENABLE: socket.socket = socks.socksocket xlog.debug("patch socks") _checking_lock.acquire() _checking_num += 1 _checking_lock.release() try: conn = httplib.HTTPSConnection("github.com", 443, timeout=30) header = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36", "accept":"application/json, text/javascript, */*; q=0.01", "accept-encoding":"gzip, deflate, sdch", "accept-language":'en-US,en;q=0.8,ja;q=0.6,zh-CN;q=0.4,zh;q=0.2', "connection":"keep-alive" } conn.request("HEAD", "/", headers=header) response = conn.getresponse() if response.status: last_check_time = time.time() report_network_ok() xlog.debug("network is ok, cost:%d ms", 1000*(time.time() - time_now)) return True except Exception as e: xlog.warn("network fail:%r", e) network_stat = "Fail" last_check_time = time.time() return False finally: _checking_lock.acquire() _checking_num -= 1 _checking_lock.release() if config.PROXY_ENABLE: socket.socket = default_socket xlog.debug("restore socket")
def _simple_check_worker(): global _checking_lock, _checking_num, network_stat, last_check_time time_now = time.time() if config.PROXY_ENABLE: socket.socket = socks.socksocket xlog.debug("patch socks") _checking_lock.acquire() _checking_num += 1 _checking_lock.release() try: conn = httplib.HTTPSConnection("www.microsoft.com", 443, timeout=30) header = {"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36", "accept":"application/json, text/javascript, */*; q=0.01", "accept-encoding":"gzip, deflate, sdch", "accept-language":'en-US,en;q=0.8,ja;q=0.6,zh-CN;q=0.4,zh;q=0.2', "connection":"keep-alive" } conn.request("HEAD", "/", headers=header) response = conn.getresponse() if response.status: last_check_time = time.time() report_network_ok() xlog.debug("network is ok, cost:%d ms", 1000*(time.time() - time_now)) return True except Exception as e: xlog.warn("network fail:%r", e) network_stat = "Fail" last_check_time = time.time() return False finally: _checking_lock.acquire() _checking_num -= 1 _checking_lock.release() if config.PROXY_ENABLE: socket.socket = default_socket xlog.debug("restore socket")
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
def build_sockets(self): self.debug.put('Socket Builder started.') count = 0 while (self.options['attacklimit'] == 0 or self.options['attacklimit'] > self.attacks) and self.running: if self.options['connectionlimit'] > self.sockets: if self.options['socksversion'] == 'SOCKS4' or self.options['socksversion'] == 'SOCKS5' or self.options['socksversion'] == 'HTTP': if self.options['socksversion'] == 'SOCKS4': proxytype = socks.PROXY_TYPE_SOCKS4 elif self.options['socksversion'] == 'SOCKS5': proxytype = socks.PROXY_TYPE_SOCKS5 else: proxytype = socks.PROXY_TYPE_HTTP s = socks.socksocket() if self.options['socksuser'] == '' and self.options['sockspass'] == '': s.setproxy(proxytype, self.options['sockshost'], self.options['socksport'], self.options['socksuser'], self.options['sockspass']) else: s.setproxy(proxytype, self.options['sockshost'], self.options['socksport']) else: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((self.options['host'], self.options['port'])) if self.options['ssl'] == True: wrap_socket(s) self.connections.put((s, 0)) self.debug.put('Socket opened, connection created.') self.attacks += 1 self.sockets += 1 except Exception, ex: self.errors.put('Could not connect. %s.' % (ex)) if self.options['timebetweenconnections'] > 0: time.sleep(self.options['timebetweenconnections']) self.debug.put('Socket Builder finished.')
def __init__(self): # ?? google.co.jp ????????? self.url = 'http://www.google.com' self.url0 = 'http://ip.cn' self.keyword = 'Anka9080' self.spider() # ?? sock5 ?? socks.set_default_proxy(socks.SOCKS5,"127.0.0.1",1080) socket.socket = socks.socksocket print len(requests.get(url = self.url, headers = HEADERS).text) # ?????? urls
def setProxy(self, host, port): int_port = int(port) socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, host, int_port) socket.socket = socks.socksocket self.port = port print 'ipify: ', self.session_get('https://api.ipify.org').content # ------------------------------------------------------------------------- # setTor proxy # -------------------------------------------------------------------------
def setTor(self, port): self.tor = True int_port = int(port) socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', int_port) socket.socket = socks.socksocket self.port = port self.restartTor() # ------------------------------------------------------------------------- # restartTor # -------------------------------------------------------------------------