Python socket.timeout() Examples
The following are 30
code examples of socket.timeout().
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
socket
, or try the search function
.
Example #1
Source File: serializekiller.py From serializekiller with The Unlicense | 10 votes |
def jenkins(url, port): try: cli_port = False ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE try: output = urllib2.urlopen('https://'+url+':'+port+"/jenkins/", context=ctx, timeout=8).info() cli_port = int(output['X-Jenkins-CLI-Port']) except urllib2.HTTPError, e: if e.getcode() == 404: try: output = urllib2.urlopen('https://'+url+':'+port, context=ctx, timeout=8).info() cli_port = int(output['X-Jenkins-CLI-Port']) except: pass except: pass
Example #2
Source File: SockPuppet.py From ALF with Apache License 2.0 | 8 votes |
def connect(self): if self.is_server: log.debug("waiting for client to connect...") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', self.port)) s.settimeout(0.1) start_time = time.time() s.listen(0) while True: try: conn, _ = s.accept() self.conn = conn break except socket.timeout: pass if self.timeout > 0 and time.time() - start_time >= self.timeout: s.close() raise RuntimeError("Timeout exceeded (%ds)" % self.timeout) self.conn.setblocking(True) else: log.debug("connecting to server (%s:%d)...", self.ip, self.port) self.conn = socket.create_connection((self.ip, self.port), self.timeout)
Example #3
Source File: utils.py From script.module.inputstreamhelper with MIT License | 6 votes |
def _http_request(url, headers=None, time_out=10): """Perform an HTTP request and return request""" log(0, 'Request URL: {url}', url=url) try: if headers: request = Request(url, headers=headers) else: request = Request(url) req = urlopen(request, timeout=time_out) log(0, 'Response code: {code}', code=req.getcode()) if 400 <= req.getcode() < 600: raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), url), response=req) except (HTTPError, URLError) as err: log(2, 'Download failed with error {}'.format(err)) if yesno_dialog(localize(30004), '{line1}\n{line2}'.format(line1=localize(30063), line2=localize(30065))): # Internet down, try again? return _http_request(url, headers, time_out) return None return req
Example #4
Source File: tnode.py From iSDX with Apache License 2.0 | 6 votes |
def interface_listener_thread(s, baddr, port): s.settimeout(10) mygeneration = generation while True: try: conn, addr = s.accept() except socket.timeout: if mygeneration == generation: continue else: output('XX', 'INFO: Listener terminating for ' + baddr + ':' + str(port)) return fromto = addr[0] + ':' + str(addr[1]) + '->' + baddr + ':' + str(port) #print 'New connection on ' + baddr + ':' + str(port) + ' from ' + addr[0] + ':' + str(addr[1]) threading.Thread(target=interface_thread , args=(conn, fromto)).start() # on-demand thread to consume data
Example #5
Source File: core.py From knob with MIT License | 6 votes |
def sendHciCommand(self, opcode, data, timeout=2): """ Send an arbitrary HCI packet by pushing a send-task into the sendQueue. This function blocks until the response is received or the timeout expires. The return value is the Payload of the HCI Command Complete Event which was received in response to the command or None if no response was received within the timeout. """ queue = Queue.Queue(1) try: self.sendQueue.put((opcode, data, queue), timeout=timeout) return queue.get(timeout=timeout) except Queue.Empty: log.warn("sendHciCommand: waiting for response timed out!") return None except Queue.Full: log.warn("sendHciCommand: send queue is full!") return None
Example #6
Source File: TCP_generic.py From XFLTReaT with MIT License | 6 votes |
def check(self): try: common.internal_print("Checking module on server: {0}".format(self.get_module_name())) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.settimeout(3) server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))) client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name()) client_fake_thread.do_check() client_fake_thread.communication(True) self.cleanup(server_socket) except socket.timeout: common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1) self.cleanup(server_socket) except socket.error as exception: if exception.args[0] == 111: common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1) else: common.internal_print("Connection error: {0}".format(self.get_module_name()), -1) self.cleanup(server_socket) return
Example #7
Source File: trip-advisor-crawler.py From trip-advisor-crawler with GNU General Public License v3.0 | 6 votes |
def getreview(domain, cityid, activity, reviewid, timeout, maxretries, basepath, force, pause): baseurl = 'http://www.tripadvisor.' + domain + '/ShowUserReviews-g' reviewurl = '%s%s-d%s-r%s' % (baseurl, cityid, activity, reviewid) path = os.sep.join((basepath, domain, str(cityid), str(activity))) filename = os.sep.join((path, str(reviewid) + '.html')) if force or not os.path.exists(filename): htmlpage = download_page(reviewurl, maxretries, timeout, pause) if htmlpage is None: print('Error downloading the review URL: ' + reviewurl) else: if not os.path.exists(path): os.makedirs(path) with codecs.open(filename, mode='w', encoding='utf8') as file: file.write(htmlpage.decode('utf-8'))
Example #8
Source File: core.py From knob with MIT License | 6 votes |
def recvPacket(self, timeout=None): """ This function polls the recvQueue for the next available HCI packet and returns it. The function checks whether it is called from the sendThread or any other thread and respectively chooses either the sendThreadrecvQueue or the recvQueue. The recvQueue is filled by the recvThread. If the queue fills up the recvThread empties the queue (unprocessed packets are lost). The recvPacket function is meant to receive raw HCI packets in a blocking manner. Consider using the registerHciCallback() functionality as an alternative which works asynchronously. """ if not self.check_running(): return None try: return self.recvQueue.get(timeout=timeout) except Queue.Empty: return None
Example #9
Source File: senseme.py From SenseMe with GNU General Public License v3.0 | 6 votes |
def _queryraw(self, msg): """An alternate version of query that does not do a default regex match on the results""" sock = socket.socket() sock.settimeout(5) sock.connect((self.ip, self.PORT)) sock.send(msg.encode("utf-8")) try: status = sock.recv(1048).decode("utf-8") LOGGER.info("Status: " + status) except socket.timeout: LOGGER.error("Socket Timed Out") else: # TODO: this shouldn't return data OR False, handle this better sock.close() LOGGER.info(str(status)) return status
Example #10
Source File: ICMP.py From XFLTReaT with MIT License | 6 votes |
def __init__(self): super(ICMP, self).__init__() self.icmp = ICMP_Proto() self.ICMP_sequence = 0 # identifier lottery self.ICMP_identifier = int(random.random() * 65535) # serverport lottery, not like it matters self.ICMP_fake_serverport = int(random.random() * 65535) # prefix to make it easier to detect xfl packets self.ICMP_prefix = "XFL" self.timeout = 2.0 # if the recv-sent>threshold: self.TRACKING_THRESHOLD = 50 # then we cut back the difference with adjust: self.TRACKING_ADJUST = 20 return
Example #11
Source File: UDP_generic.py From XFLTReaT with MIT License | 6 votes |
def check(self): try: common.internal_print("Checking module on server: {0}".format(self.get_module_name())) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))) self.comms_socket = server_socket self.serverorclient = 0 self.authenticated = False self.do_check() self.communication(True) except KeyboardInterrupt: self.cleanup() raise except socket.timeout: common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1) except socket.error: self.cleanup() raise self.cleanup() return
Example #12
Source File: senseme.py From SenseMe with GNU General Public License v3.0 | 6 votes |
def _query(self, msg): sock = socket.socket() sock.settimeout(5) sock.connect((self.ip, self.PORT)) sock.send(msg.encode("utf-8")) try: status = sock.recv(1048).decode("utf-8") LOGGER.info("Status: " + status) except socket.timeout: LOGGER.error("Socket Timed Out") else: # TODO: this shouldn't return data OR False, handle this better sock.close() LOGGER.info(str(status)) match_obj = re.match("\(.*;([^;]+)\)", status) if match_obj: return match_obj.group(1) else: return False
Example #13
Source File: udp.py From wio-cli with MIT License | 6 votes |
def send(cmd): s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.settimeout(1) flag = False for i in range(3): try: s.sendto(cmd, addr) while 1: data, a = s.recvfrom(1024) if 'ok' in data: flag = True break except socket.timeout: continue except: break if flag: break s.close() return flag
Example #14
Source File: pyopenssl.py From gist-alfred with MIT License | 6 votes |
def recv(self, *args, **kwargs): try: data = self.connection.recv(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout('The read operation timed out') else: return self.recv(*args, **kwargs) else: return data
Example #15
Source File: network.py From lifx-python with GNU Affero General Public License v3.0 | 6 votes |
def recvpacket(timeout = None): global connection if connection is None: connect() #connection.settimeout(timeout) #try: # lengthdatum, addr = connection.recvfrom(2) #except socket.timeout: # return None #connection.settimeout(None) #try: # (length, ) = struct.unpack('<H', lengthdatum) #except struct.error: # connect() # return None #data, addr = connection.recvfrom(length - 2) try: data, addr = connection.recvfrom(1024) except socket.timeout: return None packet = packetcodec.decode_packet(data) if debug: print('recvpacket(): ', packet) return packet
Example #16
Source File: connectionpool.py From jawfish with MIT License | 6 votes |
def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # See the above comment about EAGAIN in Python 3. In Python 2 we have # to specifically catch it and throw the timeout error if hasattr(err, 'errno') and err.errno in _blocking_errnos: raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # Catch possible read timeouts thrown as SSL errors. If not the # case, rethrow the original. We need to do this because of: # http://bugs.python.org/issue10272 if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
Example #17
Source File: connection.py From jawfish with MIT License | 6 votes |
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = connection.create_connection( (self.host, self.port), self.timeout, **extra_kw) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) return conn
Example #18
Source File: pyopenssl.py From jawfish with MIT License | 6 votes |
def recv(self, *args, **kwargs): try: data = self.connection.recv(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return b'' else: raise except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else: raise except OpenSSL.SSL.WantReadError: rd, wd, ed = select.select( [self.socket], [], [], self.socket.gettimeout()) if not rd: raise timeout('The read operation timed out') else: return self.recv(*args, **kwargs) else: return data
Example #19
Source File: Requests.py From Vxscan with Apache License 2.0 | 6 votes |
def __init__(self): urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) requests.packages.urllib3.disable_warnings() self.timeout = TIMEOUT self.session = requests.Session() self.headers = get_ua() if COOKIE == 'random': plain = ''.join([random.choice('0123456789') for _ in range(8)]) md5sum = hashlib.md5() md5sum.update(plain.encode('utf-8')) md5 = md5sum.hexdigest() self.headers.update({'Cookie': 'SESSION=' + md5}) else: self.headers.update(COOKIE) if SOCKS5: ip, port = SOCKS5 socks.set_default_proxy(socks.SOCKS5, ip, port) socket.socket = socks.socksocket
Example #20
Source File: Requests.py From Vxscan with Apache License 2.0 | 6 votes |
def scan(self, url): url = verify(url) try: r = self.session.get(url, timeout=self.timeout, headers=self.headers, verify=False, stream=True, allow_redirects=False) return r except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout, requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError, ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError, urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError): pass except Exception as e: logging.exception(e)
Example #21
Source File: Requests.py From Vxscan with Apache License 2.0 | 6 votes |
def post(self, url, data): url = verify(url) try: r = self.session.post(url, data=data, timeout=self.timeout, headers=self.headers, verify=False, allow_redirects=False) return r except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout, requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError, ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError, urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError): pass except Exception as e: logging.exception(e)
Example #22
Source File: Requests.py From Vxscan with Apache License 2.0 | 6 votes |
def request(self, url, method, data=None, headers=None): url = verify(url) try: if method == 'get': r = self.session.get(url, timeout=self.timeout, headers=headers, verify=False, allow_redirects=True) return r else: r = self.session.post(url, data=data, timeout=self.timeout, headers=headers, verify=False, allow_redirects=False) return r except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.Timeout, requests.exceptions.SSLError, requests.exceptions.ConnectionError, ssl.SSLError, AttributeError, ConnectionRefusedError, socket.timeout, urllib3.exceptions.ReadTimeoutError, OpenSSL.SSL.WantReadError, urllib3.exceptions.DecodeError, requests.exceptions.ContentDecodingError): pass except Exception as e: logging.exception(e)
Example #23
Source File: connectionpool.py From gist-alfred with MIT License | 6 votes |
def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # See the above comment about EAGAIN in Python 3. In Python 2 we have # to specifically catch it and throw the timeout error if hasattr(err, 'errno') and err.errno in _blocking_errnos: raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # Catch possible read timeouts thrown as SSL errors. If not the # case, rethrow the original. We need to do this because of: # http://bugs.python.org/issue10272 if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python < 2.7.4 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
Example #24
Source File: pyopenssl.py From gist-alfred with MIT License | 6 votes |
def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None): cnx = OpenSSL.SSL.Connection(self._ctx, sock) if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3 server_hostname = server_hostname.encode('utf-8') if server_hostname is not None: cnx.set_tlsext_host_name(server_hostname) cnx.set_connect_state() while True: try: cnx.do_handshake() except OpenSSL.SSL.WantReadError: if not util.wait_for_read(sock, sock.gettimeout()): raise timeout('select timed out') continue except OpenSSL.SSL.Error as e: raise ssl.SSLError('bad handshake: %r' % e) break return WrappedSocket(cnx, sock)
Example #25
Source File: pyopenssl.py From gist-alfred with MIT License | 6 votes |
def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout('The read operation timed out') else: return self.recv_into(*args, **kwargs)
Example #26
Source File: securetransport.py From gist-alfred with MIT License | 6 votes |
def send(self, data): processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLWrite( self.context, data, len(data), ctypes.byref(processed_bytes) ) if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0: # Timed out raise socket.timeout("send timed out") else: _assert_no_error(result) # We sent, and probably succeeded. Tell them how much we sent. return processed_bytes.value
Example #27
Source File: serializekiller.py From serializekiller with The Unlicense | 5 votes |
def nmap(host, *args): global shellCounter global threads global target_list # All ports to enumerate over for jboss, jenkins, weblogic, websphere port_list = ['80', '81', '443', '444', '1099', '5005', '7001', '7002', '8080', '8081', '8083', '8443', '8880', '8888', '9000', '9080', '9443', '16200'] # Are there any ports defined for this host? if not target_list[host]: found = False cmd = 'nmap --host-timeout 5 --open -p %s %s' % (','.join(port_list), host) try: p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() for this_port in port_list: if out.find(this_port) >= 0: if websphere(host, this_port) or weblogic(host, this_port) or jboss(host, this_port) or jenkins(host, this_port): found = True if found: shellCounter += 1 except ValueError, v: print " ! Something went wrong on host: %s: %s" % (host, v) return
Example #28
Source File: port_scan.py From Vxscan with Apache License 2.0 | 5 votes |
def run(self, ip): hosts = [] global PORTS, THREADNUM random.shuffle(PORTS) for i in PORTS: hosts.append('{}:{}'.format(ip, i)) try: with concurrent.futures.ThreadPoolExecutor(max_workers=THREADNUM) as executor: result = {executor.submit(self.socket_scan, i): i for i in hosts} for future in concurrent.futures.as_completed(result, timeout=3): future.result() if self.num == 1: break except (EOFError, concurrent.futures._base.TimeoutError): pass
Example #29
Source File: support.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
def _waitfor(func, pathname, waitall=False): # Perform the operation func(pathname) # Now setup the wait loop if waitall: dirname = pathname else: dirname, name = os.path.split(pathname) dirname = dirname or '.' # Check for `pathname` to be removed from the filesystem. # The exponential backoff of the timeout amounts to a total # of ~1 second after which the deletion is probably an error # anyway. # Testing on a i7@4.3GHz shows that usually only 1 iteration is # required when contention occurs. timeout = 0.001 while timeout < 1.0: # Note we are only testing for the existence of the file(s) in # the contents of the directory regardless of any security or # access rights. If we have made it this far, we have sufficient # permissions to do that much using Python's equivalent of the # Windows API FindFirstFile. # Other Windows APIs can fail or give incorrect results when # dealing with files that are pending deletion. L = os.listdir(dirname) if not (L if waitall else name in L): return # Increase the timeout and try again time.sleep(timeout) timeout *= 2 warnings.warn('tests may fail, delete still pending for ' + pathname, RuntimeWarning, stacklevel=4)
Example #30
Source File: serializekiller.py From serializekiller with The Unlicense | 5 votes |
def weblogic(url, port): try: server_address = (url, int(port)) sock = socket.create_connection(server_address, 4) sock.settimeout(2) # Send headers headers = 't3 12.2.1\nAS:255\nHL:19\nMS:10000000\nPU:t3://us-l-breens:7001\n\n' sock.sendall(headers) try: data = sock.recv(1024) except socket.timeout: return False sock.close() if "HELO" in data: mutex.acquire() print " - (possibly) Vulnerable Weblogic: " + url + " (" + str(port) + ")" saveToFile('[+] Weblogic: ' + url + ':' + str(port) + '\n') mutex.release() return True return False except socket_error: return False # Used something from https://github.com/foxglovesec/JavaUnserializeExploits