Python socket.setdefaulttimeout() Examples

The following are code examples for showing how to use socket.setdefaulttimeout(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_multiprocessing.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def test_timeout(self):
        old_timeout = socket.getdefaulttimeout()
        try:
            socket.setdefaulttimeout(0.1)
            parent, child = multiprocessing.Pipe(duplex=True)
            l = multiprocessing.connection.Listener(family='AF_INET')
            p = multiprocessing.Process(target=self._test_timeout,
                                        args=(child, l.address))
            p.start()
            child.close()
            self.assertEqual(parent.recv(), 123)
            parent.close()
            conn = l.accept()
            self.assertEqual(conn.recv(), 456)
            conn.close()
            l.close()
            p.join(10)
        finally:
            socket.setdefaulttimeout(old_timeout)

#
# Test what happens with no "if __name__ == '__main__'"
# 
Example 2
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: diagnose.py    Apache License 2.0 6 votes vote down vote up
def check_network(args):
    print('----------Network Test----------')
    if args.timeout > 0:
        print('Setting timeout: {}'.format(args.timeout))
        socket.setdefaulttimeout(10)
    for region in args.region.strip().split(','):
        r = region.strip().lower()
        if not r:
            continue
        if r in REGIONAL_URLS:
            URLS.update(REGIONAL_URLS[r])
        else:
            import warnings
            warnings.warn('Region {} do not need specific test, please refer to global sites.'.format(r))
    for name, url in URLS.items():
        test_connection(name, url, args.timeout) 
Example 3
Project: instatag   Author: Moduland   File: instatag.py    MIT License 6 votes vote down vote up
def internet(host="8.8.8.8", port=53, timeout=50):
    """
    Check Internet Connections.
    :param  host: the host that check connection to
    :param  port: port that check connection with
    :param  timeout: times that check the connnection
    :type host:str
    :type port:int
    :type timeout:int
    :return bool: True if Connection is Stable
    >>> internet() # if there is stable internet connection
    True
    >>> internet() # if there is no stable internet connection
    False
    """
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except Exception:
        return False 
Example 4
Project: Vxscan   Author: al0ne   File: rsync_unauthorized_access.py    Apache License 2.0 6 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        try:
            socket.setdefaulttimeout(1.5)
            payload = b"\x40\x52\x53\x59\x4e\x43\x44\x3a\x20\x33\x31\x2e\x30\x0a"
            socket.setdefaulttimeout(timeout)
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (ip, 873)
            sock.connect(server_address)
            sock.sendall(payload)
            initinfo = sock.recv(400)
            if b"RSYNCD" in initinfo:
                sock.sendall(b"\x0a")
            modulelist = sock.recv(200)
            sock.close()
            if len(modulelist) > 0:
                return '873 Rsync Unauthorized Access'
        except Exception as e:
            pass
            # return '27017 MongoDB fail' 
Example 5
Project: Pancas   Author: Sup3Roque   File: F4mProxy.py    GNU General Public License v2.0 6 votes vote down vote up
def start(self,stopEvent,port=PORT_NUMBER):
        global PORT_NUMBER
        global HOST_NAME
        global g_stopEvent
        print 'port',port,'HOST_NAME',HOST_NAME
        g_stopEvent = stopEvent
        socket.setdefaulttimeout(10)
        server_class = ThreadedHTTPServer
        #MyHandler.protocol_version = "HTTP/1.1"
        MyHandler.protocol_version = "HTTP/1.1"
        httpd = server_class((HOST_NAME, port), MyHandler)
        
        print "XBMCLocalProxy Starts - %s:%s" % (HOST_NAME, port)
        while(True and not stopEvent.isSet()):
            httpd.handle_request()
        httpd.server_close()
        print "XBMCLocalProxy Stops %s:%s" % (HOST_NAME, port) 
Example 6
Project: Pancas   Author: Sup3Roque   File: F4mProxy.py    GNU General Public License v2.0 6 votes vote down vote up
def start(self,stopEvent,port=PORT_NUMBER):
        global PORT_NUMBER
        global HOST_NAME
        global g_stopEvent
        print 'port',port,'HOST_NAME',HOST_NAME
        g_stopEvent = stopEvent
        socket.setdefaulttimeout(10)
        server_class = ThreadedHTTPServer
        #MyHandler.protocol_version = "HTTP/1.1"
        MyHandler.protocol_version = "HTTP/1.1"
        httpd = server_class((HOST_NAME, port), MyHandler)
        
        print "XBMCLocalProxy Starts - %s:%s" % (HOST_NAME, port)
        while(True and not stopEvent.isSet()):
            httpd.handle_request()
        httpd.server_close()
        print "XBMCLocalProxy Stops %s:%s" % (HOST_NAME, port) 
Example 7
Project: xunfeng_vul_poc   Author: muYoz   File: ThinkPHP-3.X-5.X-orderby-sql.py    GNU General Public License v3.0 6 votes vote down vote up
def check(ip, port, timeout):
    try:
        socket.setdefaulttimeout(timeout)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip, port))
        flag = "GET /?order[updatexml(1,concat(0x3a,user()),1)]=1 HTTP/1.1"
        s.send(flag)
        time.sleep(1)
        data = s.recv(1024)
        s.close()
        if 'GET' in data:
            url = 'http://' + ip + ":" + str(port) + '/?order[updatexml(1,concat(0x3a,user()),1)]=1'
            request = urllib2.Request(url)
            res_html = urllib2.urlopen(request, timeout=timeout).read(204800)
            if 'root' in res_html:
                return u"ThinkPHP 3.X order by注入漏洞"


    except Exception, e:
        pass 
Example 8
Project: NiujiaoDebugger   Author: MrSrc   File: _test_multiprocessing.py    GNU General Public License v3.0 6 votes vote down vote up
def test_timeout(self):
        old_timeout = socket.getdefaulttimeout()
        try:
            socket.setdefaulttimeout(0.1)
            parent, child = multiprocessing.Pipe(duplex=True)
            l = multiprocessing.connection.Listener(family='AF_INET')
            p = multiprocessing.Process(target=self._test_timeout,
                                        args=(child, l.address))
            p.start()
            child.close()
            self.assertEqual(parent.recv(), 123)
            parent.close()
            conn = l.accept()
            self.assertEqual(conn.recv(), 456)
            conn.close()
            l.close()
            join_process(p)
        finally:
            socket.setdefaulttimeout(old_timeout)

#
# Test what happens with no "if __name__ == '__main__'"
# 
Example 9
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testDefaultTimeout(self):
        # Testing default timeout
        # The default timeout should initially be None
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Set the default timeout to 10, and see if it propagates
        socket.setdefaulttimeout(10)
        self.assertEqual(socket.getdefaulttimeout(), 10)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), 10)
        s.close()

        # Reset the default timeout to None, and see if it propagates
        socket.setdefaulttimeout(None)
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Check that setting it to an invalid value raises ValueError
        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)

        # Check that setting it to an invalid type raises TypeError
        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") 
Example 10
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testTimeoutDefault(self):
        # passing no explicit timeout uses socket's global default
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(42)
        try:
            self.cli = socket.create_connection((HOST, self.port))
            self.addCleanup(self.cli.close)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(self.cli.gettimeout(), 42) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _testTimeoutNone(self):
        # None timeout means the same as sock.settimeout(None)
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(30)
        try:
            self.cli = socket.create_connection((HOST, self.port), timeout=None)
            self.addCleanup(self.cli.close)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(self.cli.gettimeout(), None) 
Example 12
Project: pyblish-win   Author: pyblish   File: test_ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutDefault(self):
        # default -- use global socket timeout
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            ftp = ftplib.FTP(HOST)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(ftp.sock.gettimeout(), 30)
        self.evt.wait()
        ftp.close() 
Example 13
Project: pyblish-win   Author: pyblish   File: test_ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutNone(self):
        # no timeout -- do not use global socket timeout
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            ftp = ftplib.FTP(HOST, timeout=None)
        finally:
            socket.setdefaulttimeout(None)
        self.assertIsNone(ftp.sock.gettimeout())
        self.evt.wait()
        ftp.close() 
Example 14
Project: pyblish-win   Author: pyblish   File: test_smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutNone(self):
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            smtp = smtplib.SMTP(HOST, self.port, timeout=None)
        finally:
            socket.setdefaulttimeout(None)
        self.assertIsNone(smtp.sock.gettimeout())
        smtp.close() 
Example 15
Project: pyblish-win   Author: pyblish   File: test_urllib2net.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_http_default_timeout(self):
        self.assertIsNone(socket.getdefaulttimeout())
        url = "http://www.example.com"
        with test_support.transient_internet(url):
            socket.setdefaulttimeout(60)
            try:
                u = _urlopen_with_retry(url)
            finally:
                socket.setdefaulttimeout(None)
            self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_urllib2net.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_http_no_timeout(self):
        self.assertIsNone(socket.getdefaulttimeout())
        url = "http://www.example.com"
        with test_support.transient_internet(url):
            socket.setdefaulttimeout(60)
            try:
                u = _urlopen_with_retry(url, timeout=None)
            finally:
                socket.setdefaulttimeout(None)
            self.assertIsNone(u.fp._sock.fp._sock.gettimeout()) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_urllib2net.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ftp_default_timeout(self):
        self.assertIsNone(socket.getdefaulttimeout())
        with test_support.transient_internet(self.FTP_HOST):
            socket.setdefaulttimeout(60)
            try:
                u = _urlopen_with_retry(self.FTP_HOST)
            finally:
                socket.setdefaulttimeout(None)
            self.assertEqual(u.fp.fp._sock.gettimeout(), 60) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_urllib2net.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ftp_no_timeout(self):
        self.assertIsNone(socket.getdefaulttimeout(),)
        with test_support.transient_internet(self.FTP_HOST):
            socket.setdefaulttimeout(60)
            try:
                u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
            finally:
                socket.setdefaulttimeout(None)
            self.assertIsNone(u.fp.fp._sock.gettimeout()) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_urllibnet.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        socket.setdefaulttimeout(None) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_telnetlib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutDefault(self):
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(30)
        try:
            telnet = telnetlib.Telnet(HOST, self.port)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(telnet.sock.gettimeout(), 30)
        telnet.sock.close() 
Example 21
Project: pyblish-win   Author: pyblish   File: test_telnetlib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutNone(self):
        # None, having other default
        self.assertTrue(socket.getdefaulttimeout() is None)
        socket.setdefaulttimeout(30)
        try:
            telnet = telnetlib.Telnet(HOST, self.port, timeout=None)
        finally:
            socket.setdefaulttimeout(None)
        self.assertTrue(telnet.sock.gettimeout() is None)
        telnet.sock.close() 
Example 22
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutAttribute(self):
        '''This will prove that the timeout gets through
        HTTPConnection and into the socket.
        '''
        # default -- use global socket timeout
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT)
            httpConn.connect()
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(httpConn.sock.gettimeout(), 30)
        httpConn.close()

        # no timeout -- do not use global socket default
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT,
                                              timeout=None)
            httpConn.connect()
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(httpConn.sock.gettimeout(), None)
        httpConn.close()

        # a value
        httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
        httpConn.connect()
        self.assertEqual(httpConn.sock.gettimeout(), 30)
        httpConn.close() 
Example 23
Project: pyblish-win   Author: pyblish   File: test_poplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTimeoutDefault(self):
        self.assertIsNone(socket.getdefaulttimeout())
        socket.setdefaulttimeout(30)
        try:
            pop = poplib.POP3(HOST, self.port)
        finally:
            socket.setdefaulttimeout(None)
        self.assertEqual(pop.sock.gettimeout(), 30)
        pop.sock.close() 
Example 24
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 25
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 26
Project: flasky   Author: RoseOu   File: package_index.py    MIT License 5 votes vote down vote up
def socket_timeout(timeout=15):
    def _socket_timeout(func):
        def _socket_timeout(*args, **kwargs):
            old_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(timeout)
            try:
                return func(*args, **kwargs)
            finally:
                socket.setdefaulttimeout(old_timeout)
        return _socket_timeout
    return _socket_timeout 
Example 27
Project: sic   Author: Yanixos   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 28
Project: sic   Author: Yanixos   File: package_index.py    GNU General Public License v3.0 5 votes vote down vote up
def socket_timeout(timeout=15):
    def _socket_timeout(func):
        def _socket_timeout(*args, **kwargs):
            old_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(timeout)
            try:
                return func(*args, **kwargs)
            finally:
                socket.setdefaulttimeout(old_timeout)

        return _socket_timeout

    return _socket_timeout 
Example 29
Project: motion-tracking   Author: dansbecker   File: download_images.py    MIT License 5 votes vote down vote up
def __init__(self, image_url_df, target_path='data/images', nb_workers=100):
        self._failed_to_capture_path = 'work/failed_to_capture_images.json'
        self.image_urls = image_url_df.itertuples()
        self.target_path = target_path
        self.nb_workers = nb_workers
        self.imgs_to_request = image_url_df.shape[0]
        self.imgs_previously_captured = 0
        self.imgs_requested = 0
        self.failed_img_requests = 0
        socket.setdefaulttimeout(5) 
Example 30
Project: bigquerylayers   Author: smandaric   File: package_index.py    GNU General Public License v3.0 5 votes vote down vote up
def socket_timeout(timeout=15):
    def _socket_timeout(func):
        def _socket_timeout(*args, **kwargs):
            old_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(timeout)
            try:
                return func(*args, **kwargs)
            finally:
                socket.setdefaulttimeout(old_timeout)

        return _socket_timeout

    return _socket_timeout 
Example 31
Project: AshsSDK   Author: thehappydinoa   File: util.py    MIT License 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 32
Project: AshsSDK   Author: thehappydinoa   File: package_index.py    MIT License 5 votes vote down vote up
def socket_timeout(timeout=15):
    def _socket_timeout(func):
        def _socket_timeout(*args, **kwargs):
            old_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(timeout)
            try:
                return func(*args, **kwargs)
            finally:
                socket.setdefaulttimeout(old_timeout)

        return _socket_timeout

    return _socket_timeout 
Example 33
Project: Paradrop   Author: ParadropLabs   File: discover.py    Apache License 2.0 5 votes vote down vote up
def perform_ssdp_discovery(service, timeout=5, retries=5, mx=3):
    # Standard multicast IP address and port for SSDP.
    group = ("239.255.255.250", 1900)

    message = "\r\n".join([
        "M-SEARCH * HTTP/1.1",
        "HOST: {0}:{1}",
        'MAN: "ssdp:discover"',
        "ST: {st}",
        "MX: {mx}"
    ]).format(*group, st=service, mx=mx)

    socket.setdefaulttimeout(timeout)

    sources = set()
    for _ in range(retries):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        sock.sendto(message.encode('utf-8'), group)
        while True:
            try:
                data, addr = sock.recvfrom(1024)
                response = SsdpResponse(data, addr)
                if addr[0] not in sources:
                    # We only want to return each node once.
                    sources.add(addr[0])
                    yield response
            except socket.timeout:
                break 
Example 34
Project: MetrixReloaded   Author: Scrounger   File: MetrixReloadedHelper.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def isconnected(logger, logPrefix="", host='8.8.8.8', port=53, timeout=1):
    try:
        socket.setdefaulttimeout(timeout)
        host = socket.gethostbyname('www.google.com')
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except Exception:
        logger.warn("%s no internet connection!", logPrefix)
        return False 
Example 35
Project: openhatch   Author: campbe13   File: mail.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def send(self, message):
        if supports_timeout:
            self._send(message, timeout=self.timeout)
        else:
            import socket
            old_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(self.timeout)
            try:
                self._send(message)
            finally:
                socket.setdefaulttimeout(old_timeout) 
Example 36
Project: openhatch   Author: campbe13   File: beat.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def start_scheduler(self, logger=None):
        c = self.colored
        if self.pidfile:
            pidlock = platforms.create_pidlock(self.pidfile).acquire()
            atexit.register(pidlock.release)
        beat = self.Service(app=self.app,
                            logger=logger,
                            max_interval=self.max_interval,
                            scheduler_cls=self.scheduler_cls,
                            schedule_filename=self.schedule)

        print(str(c.blue("__    ", c.magenta("-"),
                  c.blue("    ... __   "), c.magenta("-"),
                  c.blue("        _\n"),
                  c.reset(self.startup_info(beat)))))
        if self.socket_timeout:
            logger.debug("Setting default socket timeout to %r",
                         self.socket_timeout)
            socket.setdefaulttimeout(self.socket_timeout)
        try:
            self.install_sync_handler(beat)
            beat.start()
        except Exception, exc:
            logger.critical("celerybeat raised exception %s: %r\n%s",
                            exc.__class__, exc, traceback.format_exc(),
                            exc_info=sys.exc_info()) 
Example 37
Project: oscrypto   Author: wbond   File: test_tls.py    MIT License 5 votes vote down vote up
def test_tls_error_ftp(self):
        try:
            def_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(5)
            make_socket_server(8021, lambda s, d: s.send(b'220 Welcome to FooFTP\n'))
            with assert_exception(self, errors.TLSError, 'remote end closed the connection|server responded using FTP'):
                tls.TLSSocket('localhost', 8021)
        finally:
            socket.setdefaulttimeout(def_timeout) 
Example 38
Project: Vxscan   Author: al0ne   File: docker_unauthorized_access.py    Apache License 2.0 5 votes vote down vote up
def check(url, ip, ports, apps):
    socket.setdefaulttimeout(2)
    if verify(vuln, ports, apps):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip, 2375))
            payload = "GET /containers/json HTTP/1.1\r\nHost: %s:%s\r\n\r\n" % (ip, 2375)
            s.send(payload.encode())
            recv = s.recv(1024)
            if b"HTTP/1.1 200 OK" in recv and b'Docker' in recv and b'Api-Version' in recv:
                return '2375 Docker unauthorized success'
        except Exception as e:
            # return '2375 Docker  Failed'
            pass 
Example 39
Project: Vxscan   Author: al0ne   File: zookeeper_unauthorized_access.py    Apache License 2.0 5 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        try:
            socket.setdefaulttimeout(1.5)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip, 2181))
            s.send(b'success')
            data = s.recv(1024)
            if b'Environment' in data:
                return 'zookeeper://%s:2181' % ip
        except Exception as e:
            pass 
Example 40
Project: Vxscan   Author: al0ne   File: port_scan.py    Apache License 2.0 5 votes vote down vote up
def socket_scan(self, hosts):
        global PROBE
        response = ''
        socket.setdefaulttimeout(2)
        ip, port = hosts.split(':')
        try:
            if len(self.port) < 30:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                result = sock.connect_ex((ip, int(port)))
                # 建立3次握手成功
                if result == 0:
                    try:
                        for i in PROBE:
                            sock.sendall(i.encode())
                            response = sock.recv(512)
                            sock.close()
                            # 发送payload 获取响应 来判断服务
                            if response:
                                self.regex(response, port)
                            else:
                                proto = {"server": get_server(port), "port": port, "banner": ''}
                                self.out.append(proto)
                            break
                    except socket.timeout:
                        proto = {"server": get_server(port), "port": port, "banner": ''}
                        self.out.append(proto)

                    self.port.append(port)

            else:
                self.num = 1

        except (socket.timeout, ConnectionResetError, OSError):
            pass
        except Exception as e:
            # traceback.print_exc(e)
            logging.exception(e) 
Example 41
Project: Repobot   Author: Desgard   File: util.py    MIT License 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 42
Project: Repobot   Author: Desgard   File: package_index.py    MIT License 5 votes vote down vote up
def socket_timeout(timeout=15):
    def _socket_timeout(func):
        def _socket_timeout(*args, **kwargs):
            old_timeout = socket.getdefaulttimeout()
            socket.setdefaulttimeout(timeout)
            try:
                return func(*args, **kwargs)
            finally:
                socket.setdefaulttimeout(old_timeout)

        return _socket_timeout

    return _socket_timeout 
Example 43
Project: JukeBox   Author: gauravsarkar97   File: util.py    MIT License 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 44
Project: chattR   Author: patrickstocklin   File: util.py    GNU General Public License v2.0 5 votes vote down vote up
def socket_timeout(seconds=15):
    cto = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(seconds)
        yield
    finally:
        socket.setdefaulttimeout(cto) 
Example 45
Project: ftpscout   Author: RubenRocha   File: ftpscout.py    GNU General Public License v3.0 5 votes vote down vote up
def get_banner(host,port):
	socket.setdefaulttimeout(3.5)
	s = socket.socket()
	try:
		s.connect((host, port))
		ans = s.recv(1024)
		s.close()
		ans = ans.decode().rstrip().replace("\r", "").replace("\n", "\n\t")
		if len(ans) == 0:
			return "Empty"
		else:
			return ans
	except Exception as e:
		return "Error obtaining banner" 
Example 46
Project: ftpscout   Author: RubenRocha   File: ftpscout.py    GNU General Public License v3.0 5 votes vote down vote up
def port_check(host, port):
	try:
		socket.setdefaulttimeout(1)
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		res = s.connect_ex((host,port))
		s.close()
		return True if res == 0 else False
	except Exception as e:
		return False 
Example 47
Project: watchdog   Author: flipkart-incubator   File: lswww.py    Apache License 2.0 5 votes vote down vote up
def browse(self, web_resource):
        """Extract urls from a webpage and add them to the list of urls
        to browse if they aren't in the exclusion list"""
        url = web_resource.url

        # We don't need destination anchors
        current_full_url = url.split("#")[0]
        # Url without query string
        current = current_full_url.split("?")[0]
        # Get the dirname of the file
        currentdir = "/".join(current.split("/")[:-1]) + "/"

        # Timeout must not be too long to block big documents
        # (for exemple a download script)
        # and not too short to give good results
        socket.setdefaulttimeout(self.timeout)

        headers = {}
        headers["user-agent"] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        try:
            resp = self.h.send(web_resource, headers=headers)
        except socket.timeout:
            self.excluded.append(url)
            return False
        except requests.exceptions.Timeout:
            self.excluded.append(url)
            return False
        except socket.error, msg:
            if msg.errno == 111:
                print(_("Connection refused!"))
            self.excluded.append(url)
            return False 
Example 48
Project: watchdog   Author: flipkart-incubator   File: HTTP.py    Apache License 2.0 5 votes vote down vote up
def setTimeOut(self, timeout=6.0):
        "Set the time to wait for a response from the server."
        self.timeout = timeout
        socket.setdefaulttimeout(self.timeout) 
Example 49
Project: watchdog   Author: flipkart-incubator   File: lswww.py    Apache License 2.0 5 votes vote down vote up
def browse(self, web_resource):
        """Extract urls from a webpage and add them to the list of urls
        to browse if they aren't in the exclusion list"""
        url = web_resource.url

        # We don't need destination anchors
        current_full_url = url.split("#")[0]
        # Url without query string
        current = current_full_url.split("?")[0]
        # Get the dirname of the file
        currentdir = "/".join(current.split("/")[:-1]) + "/"

        # Timeout must not be too long to block big documents
        # (for exemple a download script)
        # and not too short to give good results
        socket.setdefaulttimeout(self.timeout)

        headers = {}
        headers["user-agent"] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        try:
            resp = self.h.send(web_resource, headers=headers)
        except socket.timeout:
            self.excluded.append(url)
            return False
        except requests.exceptions.Timeout:
            self.excluded.append(url)
            return False
        except socket.error, msg:
            if msg.errno == 111:
                print(_("Connection refused!"))
            self.excluded.append(url)
            return False 
Example 50
Project: watchdog   Author: flipkart-incubator   File: HTTP.py    Apache License 2.0 5 votes vote down vote up
def setTimeOut(self, timeout=6.0):
        "Set the time to wait for a response from the server."
        self.timeout = timeout
        socket.setdefaulttimeout(self.timeout)