• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socks.setdefaultproxy函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socks.setdefaultproxy函数的典型用法代码示例。如果您正苦于以下问题:Python setdefaultproxy函数的具体用法?Python setdefaultproxy怎么用?Python setdefaultproxy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了setdefaultproxy函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: dnsCheck

def dnsCheck(path):
    """
    DNS Poisoning Check
    """
    try:
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        socket.socket = socks.socket

        print('[+] Checking DNS ')
        for domain in domains:
            ipv4 = socket.gethostbyname(domain)
            for p_d in check_domain_poison_results:
                if str(p_d.domain) == str(domain):
                    found = False
                    for d_ip in p_d.address:
                        if str(ipv4) == str(d_ip):
                            found = True
                            break
                    if found == False:
                        print('[+] ALERT:DNS SPOOFING FOUND: name: %s ip: %s  (path: %s )' % (domain, ipv4, path) )
                    else:
                        print('[+] Check DNS (%s) seems to be OK' % domain)
    except Exception as err:
        print('[-] Error: %s' % err)
        traceback.print_exc()

    socket.close()
    return time.time()
开发者ID:jothatron,项目名称:malexit,代码行数:28,代码来源:findMaliciousExitPoints.py


示例2: fetchGFWList

def fetchGFWList(config):
    import socks
    import socket
    import urllib2

    proxy_type = config["gfwProxyType"]
    proxy_host = config["gfwProxyHost"]
    proxy_port = config["gfwProxyPort"]
    proxy_user = config["gfwProxyUsr"]
    proxy_pwd = config["gfwProxyPwd"]

    if proxy_type == socks.PROXY_TYPE_SOCKS4 or proxy_type == socks.PROXY_TYPE_SOCKS5:
        socks.setdefaultproxy(proxy_type, proxy_host, proxy_port, True, proxy_user, proxy_pwd)
        socket.socket = socks.socksocket
    elif proxy_type == socks.PROXY_TYPE_HTTP:
        http_proxy = "{}:{}".format(proxy_host, proxy_port)
        if proxy_user or proxy_pwd:
            http_proxy = "{}:{}@{}".format(proxy_user, proxy_pwd, http_proxy)

        proxy_handler = urllib2.ProxyHandler({"http": http_proxy})
        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)

    if config["debug"]:
        httpHandler = urllib2.HTTPHandler(debuglevel=1)
        httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
        opener = urllib2.build_opener(httpHandler, httpsHandler)
        urllib2.install_opener(opener)

    response = urllib2.urlopen(config["gfwUrl"])
    gfwlistModified = response.info().getheader("last-modified")
    gfwlistContent = response.read()

    return gfwlistContent, gfwlistModified
开发者ID:kenchou,项目名称:gfwlist2pac,代码行数:34,代码来源:gfwlist2pac.py


示例3: __init__

 def __init__(self, server, config = None):
     threading.Thread.__init__(self)
     self.daemon = True
     self.config = config if config is not None else SimpleConfig()
     self.lock = threading.Lock()
     self.is_connected = False
     self.debug = False # dump network messages. can be changed at runtime using the console
     self.message_id = 0
     self.unanswered_requests = {}
     # are we waiting for a pong?
     self.is_ping = False
     # parse server
     self.server = server
     self.host, self.port, self.protocol = self.server.split(':')
     self.port = int(self.port)
     self.use_ssl = (self.protocol == 's')
     self.proxy = self.parse_proxy_options(self.config.get('proxy'))
     if self.proxy:
         self.proxy_mode = proxy_modes.index(self.proxy["mode"]) + 1
         socks.setdefaultproxy(self.proxy_mode, self.proxy["host"], int(self.proxy["port"]))
         socket.socket = socks.socksocket
         # prevent dns leaks, see http://stackoverflow.com/questions/13184205/dns-over-proxy
         def getaddrinfo(*args):
             return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
         socket.getaddrinfo = getaddrinfo
开发者ID:1gabo,项目名称:electrum,代码行数:25,代码来源:interface.py


示例4: loadSocketModule

def loadSocketModule(loadModule = None, module = None):
	proxyLoad = False
	reload(socket)
	setattr(socket, '__reloaded__', False)
	if ( loadModule is None and USE_PROXY == 'True' ) or loadModule :
		## http://sourceforge.net/projects/socksipy/
		## or install the Fedora liked python-SocksiPy package
		try :
			import socks
			proxyLoad = True
		except : pass
		finally :
			if proxyLoad :
				# for old SocksiPy versions
				if hasattr(socks, '_socket') :
					socks._socket.setdefaulttimeout(TIMEOUT)
				"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])"""
				proxytype, addr, port, rdns, username, password = readProxySettings(socks)
				#print proxytype, addr, port, rdns, username, password
				socks.setdefaultproxy(proxytype, addr, port, rdns, username, password)
				socket.socket = socks.socksocket
				setattr(socket, '__reloaded__', True)
	if type(module) == ModuleType :
		reload(module)
		setattr(module, '__reloaded__', getattr(socket, '__reloaded__'))
	# for checking proxy availability or external IP uncomment below
	#ip = getExternalIP()
	#print "External IP: %s ; Reloaded: %s" % (ip, getattr(socket, '__reloaded__'))

	return proxyLoad
开发者ID:F1ash,项目名称:pyqt-mail-checker,代码行数:30,代码来源:MailFunc.py


示例5: set

	def set(self, type=socks.PROXY_TYPE_SOCKS5, host='127.0.0.1', port='9050'):
		"""
		configure and active current proxy. change arguments as needed
		"""
		socks.setdefaultproxy(type, host, port)
		self.socket = socks.socksocket
		self.running = True
开发者ID:champ1,项目名称:misc-snippets,代码行数:7,代码来源:proxy_wrap.py


示例6: run

    def run(self):                    
        config = queue.get()
        config["DataDirectory"] = tempfile.gettempdir() + os.pathsep + str(self.port)
        config["SocksPort"] = str(self.port)
        
        print("Testing " + config["ExitNodes"] + " on port " + str(self.port))

        try:
            tor_process = stem.process.launch_tor_with_config(config)
                      
            password = randomPass()
                            
            data = {
                "user": "admin",
                "password": password
            }
            
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", self.port)
            socket.socket = socks.socksocket

            socket.getaddrinfo = getaddrinfo
            socket.setdefaulttimeout(10)
                
            print("Content: " + requests.get(PANEL_URL, data=data, timeout=5).content.decode())
                                                
            tor_process.kill()
        except Exception as e: 
            print(str(e))
                
        file.close()
开发者ID:redpois0n,项目名称:tor-login-faker,代码行数:30,代码来源:send.py


示例7: download_file

def download_file():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "192.168.1.166", 9050)
    socket.socket = socks.socksocket
    #u = urllib2.urlopen('http://releases.ubuntu.com/15.04/ubuntu-15.04-desktop-i386.iso')#.read()
    #u = urllib2.urlopen('https://www.google.com')#.read()
    u = urllib2.urlopen('https://raw.githubusercontent.com/mcoughli/xilinx_zedboard_c/master/test_blob')
    #file_name = 'ubuntu-15.04-desktop-i386.iso'
    file_name = 'test_blob'
    f = open(file_name, 'w')
    meta = u.info()
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    
    downloaded = 0
    start_time = timeit.default_timer()
    while True:
        buffer = u.read(8192)
        if not buffer:
            break
        downloaded += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (downloaded, downloaded * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print status,
    elapsed = timeit.default_timer() - start_time
    print 'Average KB/s: ' + str(downloaded/1024/elapsed)
    return downloaded, elapsed
开发者ID:IngenicC,项目名称:xilinx_zedboard_c,代码行数:27,代码来源:tor_upload_test.py


示例8: start

def start():

    for d in gConfig["REMOTE_DNS_LIST"]:
        heapq.heappush(dnsHeap, (1,d))
 
    try:
        response = DNS.Request().req(name="jjproxy.liruqi.info", qtype="A", protocol="udp", port=gConfig["DNS_PORT"], server=gConfig["REMOTE_DNS_LIST"][0])
        for a in response.answers:
            if a['typename'] == 'A':
                ip = a["data"]
                gConfig["HTTP_PROXY"] = ip
                gConfig["HTTP_PROXY_PORT"] = 25
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, 21)

    except:
        print "HTTP_PROXY resolve failed, exit."
        exit(1)

    print "Set your browser's HTTP/HTTPS proxy to 127.0.0.1:%d"%(gOptions.port)
    print "You can configure your proxy var http://127.0.0.1:%d"%(gOptions.port)
    if gConfig['CONFIG_ON_STARTUP']:
        try: 
            import webbrowser
            webbrowser.open("http://127.0.0.1:%d"%gOptions.port)
        except:
            pass

    server = ThreadingHTTPServer(("0.0.0.0", gOptions.port), ProxyHandler)
    try: server.serve_forever()
    except KeyboardInterrupt: exit()
开发者ID:GFW-Fucker,项目名称:jjproxy,代码行数:30,代码来源:jjproxy.py


示例9: maxtest

def maxtest(SOCKS_PORT):

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

    print term.format("Starting Tor:\n", term.Attr.BOLD)
    """
    tor_process = stem.process.launch_tor_with_config(
        config = {
            'SocksPort': str(SOCKS_PORT),
            'ExitNodes': '{ru}',
        },
        init_msg_handler = print_bootstrap_lines,
    )
    """
    tor_process = stem.process.launch_tor_with_config(
        config = {
            'SocksPort': str(SOCKS_PORT),
        },
        init_msg_handler = print_bootstrap_lines,
    )

    print term.format("\nChecking our endpoint:\n", term.Attr.BOLD)
    print term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE)



    tor_process.kill()    # stops tor
开发者ID:maxberggren,项目名称:sinus,代码行数:28,代码来源:tor.py


示例10: main

def main():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 7070)
    socket.socket = socks.socksocket

    actress_down()

    collection_down()
开发者ID:liyunhai,项目名称:res-auto,代码行数:7,代码来源:xart_image_down.py


示例11: GetFileHosts

    def GetFileHosts(self, url, list, lock, message_queue):
        from entertainment.net import Net

        net = Net(do_not_cache_if_any=do_no_cache_keywords_list)

        custom_url = self.get_url()

        if self.Settings().get_setting("proxy") == "true":
            import socks

            (proxy, port) = self.get_proxy()
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy, port)
            net.set_socket_class(socks.socksocket)

        content = common.unescape(common.str_conv(net.http_GET(url).content))

        import re

        for sq in re.finditer(r"<span class=quality_(.+?)>.+?<a href=\".+?external.+?url=(.+?)&", content):

            quality = sq.group(1).upper()

            if quality == "UNKNOWN":
                continue

            import base64

            host_url = base64.b64decode(sq.group(2))
            if not "affbuzz" in host_url.lower():
                self.AddFileHost(list, quality, host_url)
开发者ID:bialagary,项目名称:mw,代码行数:30,代码来源:primewire_mvi_mvs_tvi_tvs_cst.py


示例12: send_to_peers

def send_to_peers():
    while True:
        error = 0
        peers_conf = ConfigParser.ConfigParser()
        peers_conf.read('conf/peers.ini')
        for i in range(len(peers_conf.sections())):
            if peers_conf.getboolean(peers_conf.sections()[i], 'Tor'):
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
            else:
                socks.setdefaultproxy()
            socket.socket = socks.socksocket
            s = socket.socket()
            try:
                s.connect((peers_conf.get(peers_conf.sections()[i], 'host'), peers_conf.getint(peers_conf.sections()[i], 'port')))
                hostlist = open("conf/host.txt", "r")
                for ligne in hostlist:
                    s.send(ligne)
                hostlist.close()
                s.close()
            except:
                s.close()
                print "\0034connexion impossible"
                error = error +1
            i=i+1
        if error == len(peers_conf.sections()): 
            print "Error aucun pair disponible"
        error = 0
        time.sleep(3600)
开发者ID:GHOSTnew,项目名称:dot-f2f,代码行数:28,代码来源:main.py


示例13: handle_proxy

    def handle_proxy(self):
        if self.proxy_enabled:
            import socks

            proxy_type = getattr(socks, "PROXY_TYPE_" + self.proxy_type)
            socks.setdefaultproxy(proxy_type, self.proxy_host, self.proxy_port)
            socket.socket = socks.socksocket
开发者ID:polyrabbit,项目名称:sogou-proxy,代码行数:7,代码来源:proxy.py


示例14: setTor

	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()
开发者ID:Buni,项目名称:primedicebot,代码行数:7,代码来源:primeDiceClass.py


示例15: run

    def run(self):
        while True:
            config = self.queue.get()

            config['DataDirectory'] = '/tmp/tor_data_%s' % (config['SocksPort'])
            self.config = config

            self.log('connecting...')

            opened = False
            with Timeout(self.timeout, False):
                self.tor_process = stem.process.launch_tor_with_config(config=self.config, timeout=None)
                self.tor_process.stdout.close()
                opened = True

            if not opened:
                self.log('connection failed', Log.LOG_ERROR)
                return self.cleanup()

            self.log('connected!')

            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', int(self.config['SocksPort']))
            socket.socket = socks.socksocket

            socket.getaddrinfo = getaddrinfo
            socket.setdefaulttimeout(self.timeout)

            self.check()
            self.cleanup()
开发者ID:intchloe,项目名称:BADONIONS,代码行数:29,代码来源:ssh.py


示例16: search_lyrics

def search_lyrics(query):
    
    # Set proxy
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
    socket.socket = socks.socksocket
    
    br = mechanize.Browser()
    # Cookie Jar
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    # Browser options
    br.set_handle_equiv(True)
    br.set_handle_gzip(False)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    # Follows refresh 0 but not hangs on refresh > 0
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1)

    # Want debugging messages?
    br.set_debug_http(False)
    br.set_debug_redirects(False)
    br.set_debug_responses(False)

    br.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 7.0b;Windows NT 5.1)')]
    br.clear_history()

#   sit to get to is http://www.songlyrics.com/
    url_prexif = "http://"
    Site_Name = 'www.songlyrics.com/'

    full_url = url_prexif + Site_Name

    try:    
        br.open(full_url)
    except IOError: 
        print 'Failure to open site' #Handle failure 
        sys.exit(0)
    
    br.select_form(name='searchForm')
    br['searchW'] = query

# submit it 
    br.submit()
# get full list of possible urls    
    responce = BeautifulSoup(br.response().read())
           
    lyrics = []    
    for block in responce.findAll('div',{'class':'serpresult'}):
        link = block.find('a',href=True)
        page = BeautifulSoup(urllib2.urlopen(link['href']))
        pre_processed_page = (str(page.find('p',{'class':'songLyricsV14'})))
        processed_page = clean_page_songlyrics(pre_processed_page)
        lyrics.append(processed_page)
    if(lyrics == None):
        lyrics = 'Lyrics not found'
        
    return lyrics
开发者ID:Techno-wizard,项目名称:python-spellbook,代码行数:60,代码来源:songlyrics.py


示例17: simulateIMAPsession

def simulateIMAPsession(username, password, imapHost, imapDomainName):
    try:
        # Tunnel through socksipy to Tor, wrapping imaplib through it
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
        socks.socket.setdefaulttimeout(30)
        socks.wrapmodule(imaplib)
        # So let's log in and let the fun begin
        mail = imaplib.IMAP4(imapHost, 143)
        mail.login(username+'@'+imapDomainName, password)
        print "namespace", mail.namespace()
        print "lsub", mail.lsub()
        print "list inbopx", mail.list("", "INBOX")
        selectanswer = mail.select("INBOX")
        print "select inbox",selectanswer
        responsecode, data = selectanswer
        lastmail = data[0]
        fetchflag = lastmail + ":*"
        print "fetch uid" , mail.fetch(fetchflag,"(FLAGS)")
        # Bye, IMAP server
        mail.logout()
        socket.socket = socks._orgsocket
    except Exception:
        raise
    finally:
        try:
            mail.logout()
            mail.shutdown()
        except Exception:
            pass
        finally:
            socket.socket = socks._orgsocket
开发者ID:mmulazzani,项目名称:HoneyConnector,代码行数:31,代码来源:ClientMain.py


示例18: youtube_search

def youtube_search(options):
    socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, PROXY_HOST, PROXY_PORT)
    socket.socket = socks.socksocket

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                    developerKey=DEVELOPER_KEY)
    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = youtube.search().list(
        q=options['q'],
        part='id,snippet',
        maxResults=options['max_results']
        ).execute()

    videos = []
    channels = []
    playlists = []

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    for search_result in search_response.get('items', []):
        # print search_result
        if search_result['id']['kind'] == 'youtube#video':
          videos.append('%s (%s)' % (search_result['snippet']['title'],
                                     search_result['id']['videoId']))
        elif search_result['id']['kind'] == 'youtube#channel':
          channels.append('%s (%s)' % (search_result['snippet']['title'],
                                       search_result['id']['channelId']))
        elif search_result['id']['kind'] == 'youtube#playlist':
          playlists.append('%s (%s)' % (search_result['snippet']['title'],
                                        search_result['id']['playlistId']))

    print('Videos:\n', '\n'.join(videos), '\n')
    print('Channels:\n', '\n'.join(channels), '\n')
    print('Playlists:\n', '\n'.join(playlists), '\n')
开发者ID:WiconWang,项目名称:Mod_Spider,代码行数:35,代码来源:youtube_api.py


示例19: tunnel

def tunnel(port_src, port_dst):
    # sock = socks.socksocket()
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, SOCKS_HOST, SOCKS_PORT, False)
    # sock.connect((SSH_SERVER_HOST, 22))
    paramiko.client.socket.socket = socks.socksocket
    client = paramiko.SSHClient()
    # client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    # client.connect(hostname=SSH_SERVER_HOST, port=SSH_SERVER_PORT, username=USERNAME, password=PASSWORD)

    # t = paramiko.Transport(sock)

    verbose('Connecting to ssh host %s:%d ...' % (SSH_SERVER_HOST, SSH_SERVER_PORT))
    try:
        # t.connect(None, username='nuno', password='nuno')
        client.connect(hostname=SSH_SERVER_HOST, port=SSH_SERVER_PORT, username=USERNAME, password=PASSWORD)
        transport = client.get_transport()
        forward_tunnel(port_src, SSH_SERVER_HOST, port_dst, transport)
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (SSH_SERVER_HOST, SSH_SERVER_PORT, e))
        sys.exit(1)

    verbose('Now forwarding port %d to %s:%d ...' % (port_src, SSH_SERVER_HOST, port_dst))

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print('C-c: Port forwarding stopped.')
        sys.exit(0)
开发者ID:danifss,项目名称:sar-1516-proj-g1,代码行数:30,代码来源:SshClient.py


示例20: request_and_save_img

    def request_and_save_img(u, p, ua, a, pause, time_out):
        start = time.time()
        opener = urllib2.build_opener()
        opener.addheaders = [('User-Agent', ua)]
        i = 0
        the_proof = True
        while i < int(a) and the_proof:
            try:
                response = opener.open(u, timeout=float(time_out))
                the_proof = False
            except urllib2.HTTPError as error:
                the_proof = True
                logging.debug('- Error at attempt number: {0} with image url: {1} -'.format(str(error.code), str(u)))
                i += 1
                time.sleep(float(pause))
        if the_proof:
            stop = time.time() - start
            message = 'Error after {0} seconds, while timeout was: {1} -\n'.format(str(stop), str(time_out))
            message += 'Error after {0} attempts, while saving image: {1} -'.format(str(a), str(u))
            logging.debug(message)
            socks.setdefaultproxy()
            EmailNotifiers.debug_error_Call(message)
            exit(1)
        html_data = response.read()

        try:
            f = open(p, 'w')
            f.write(html_data)
            f.close()
        except IOError:
            logging.info('- ERROR in request_and_save with file {0} -'.format(str(p)))
开发者ID:bl4ckh0l3z,项目名称:bspotreader,代码行数:31,代码来源:utility.py



注:本文中的socks.setdefaultproxy函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socks.socksocket函数代码示例发布时间:2022-05-27
下一篇:
Python socks.set_default_proxy函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap