当前位置: 首页>>代码示例>>Python>>正文


Python socks.wrapmodule函数代码示例

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


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

示例1: dispatch

  def dispatch(self,noise=None):
      charset.add_charset('utf-8', charset.SHORTEST)
      if self.args.encrypted and self.args.encrypted.lower() not in ['false','no','0']:
	msg = MIMEText(fake_pgp_msg(), _charset='utf-8')
      else:
        msg = MIMEText(noise if noise else self.args.body, _charset='utf-8')
      msg['Subject'] = self.args.subject
      msg['From'] = self.args.sender
      if ',' in self.args.to:
	random.seed()
	msg['To'] = random.choice(self.args.to.split(', '))
      else:
        msg['To'] = self.args.to
    
      if self.args.proxy:
          # Let's use a Tor SOCKS proxy, if available. Obviously, start Tor before running this program
          socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, 'localhost', self.args.proxy)
          s = socks.socksocket()
          s.connect(('example.com', 80))
          s.close()
          socks.wrapmodule(smtplib)
    
      # Use STARTTLS for added security
      smtpserver = smtplib.SMTP(self.args.server)
      smtpserver.starttls()
      smtpserver.set_debuglevel(True)
      smtpserver.login(self.args.sender,self.args.passwd)
      try:
        smtpserver.sendmail(self.args.sender, [self.args.to], msg.as_string())
      finally:
        smtpserver.close()
  
      return "Successfully sent mail"
开发者ID:dismantl,项目名称:NOISE,代码行数:33,代码来源:noise_dispatch.py

示例2: 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

示例3: send_http

    def send_http(self, messages, channel='default'):
        import urllib2, json, time, cookielib
        
        if self.proxy:
            import socks
            socks.setdefaultproxy(proxy_modes.index(self.proxy["mode"]) + 1, self.proxy["host"], int(self.proxy["port"]) )
            socks.wrapmodule(urllib2)

        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        urllib2.install_opener(opener)

        t1 = time.time()

        data = []
        for m in messages:
            method, params = m
            if type(params) != type([]): params = [params]
            data.append( { 'method':method, 'id':self.message_id, 'params':params } )
            self.unanswered_requests[self.message_id] = method, params, channel
            self.message_id += 1

        if data:
            data_json = json.dumps(data)
        else:
            # poll with GET
            data_json = None 

            
        headers = {'content-type': 'application/json'}
        if self.session_id:
            headers['cookie'] = 'SESSION=%s'%self.session_id

        req = urllib2.Request(self.connection_msg, data_json, headers)
        response_stream = urllib2.urlopen(req)

        for index, cookie in enumerate(cj):
            if cookie.name=='SESSION':
                self.session_id = cookie.value

        response = response_stream.read()
        self.bytes_received += len(response)
        if response: 
            response = json.loads( response )
            if type(response) is not type([]):
                self.queue_json_response(response)
            else:
                for item in response:
                    self.queue_json_response(item)

        if response: 
            self.poll_interval = 1
        else:
            if self.poll_interval < 15: 
                self.poll_interval += 1
        #print self.poll_interval, response

        self.rtime = time.time() - t1
        self.is_connected = True
开发者ID:Azelphur,项目名称:electrum,代码行数:59,代码来源:interface.py

示例4: decorator

 def decorator(*args):
     print instance.config.main.proxyaddress
     host, port = instance.config.main.proxyaddress.split(":")
     socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, host, int(port))
     # Wrap the modules into socks
     for module in self.modules:
         socks.wrapmodule(module)
     return self.f(instance, *args)
开发者ID:funsim,项目名称:ooni-probe,代码行数:8,代码来源:__init__.py

示例5: getEpisodes

    def getEpisodes(self, combinedShowID, proxy):
        
        # A bit hacky ...
        # Split into "title" style id and URL
        splitString = re.findall('(.*)__(.*)',combinedShowID)
        titleShowID = str(splitString[0][0])
        showId = str(splitString[0][1]).split('=')[-1]
               
        # Check if proxy enabled & set
        if proxy['proxy'] == True and proxy['proxy_address'] <> "" and proxy['proxy_port'] <> 0:
            # Set the proxy information
            if proxy['proxy_type'] == 'HTTP':
                socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, proxy['proxy_address'], proxy['proxy_port'])
            elif proxy['proxy_type'] == 'SOCKS4':
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, proxy['proxy_address'], proxy['proxy_port'])
            elif proxy['proxy_type'] == 'SOCKS5':
                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, proxy['proxy_address'], proxy['proxy_port'])

            # Wrap urllib2 module
            socks.wrapmodule(urllib2)
        
        page = urllib2.urlopen(PROGRAMME_URL + titleShowID)
        soup = BeautifulStoneSoup(page, selfClosingTags=['link','category','media:player','media:thumbnail'])
        page.close()
        
        items = soup.findAll('entry')
        if not items:
            # That works for some things, but not this show ... 
            # OK, that didn't work. Try using the ID to search for episodes
            urlShowID = EPISODE%(showId)            
            page = urllib2.urlopen(urlShowID)
            soup = BeautifulStoneSoup(page, selfClosingTags=['link','category','media:player','media:thumbnail'])
            page.close()            
            items = soup.findAll('entry')
            
        for item in items:
            # This finds the entire element ... get the bit we want
            linkElement = item.find(attrs={'type' : 'application/atom+xml'})
            mymatch = re.findall('href="(.*)"' , str(linkElement)) 
            title = self.getStringFor(item, 'title')
            published = self.getStringFor(item, 'published')
            desc =  self.getStringFor(item, 'media:description')
            thumb =  self.getStringFor(item, 'media:thumbnail', 'url', LOGOICON)
            # Duration doesn't seem to make any difference ... 
            duration = str(int(self.getStringFor(item, 'rte:duration','ms'))/1000/60)
            
            yield { 'PlotOutline'  : title,
                    'Duration'     : duration,
                    'Studio'       : CHANNEL,
                    'Year'         : int("%s" % (published[ : 4 ])),
                    'Date'         : "%s-%s-%s" % ( published[ 8 : 10], published[ 5 : 7 ], published[ : 4 ]),
                    'Thumb'        : thumb,
                    'Channel'      : CHANNEL,
                    'url'          : mymatch[0],
                    'Title'        : title,
                    'mode'         : MenuConstants.MODE_PLAYVIDEO,
                    'Plot'         : desc
                    }
开发者ID:shanemeagher,项目名称:VODieR,代码行数:58,代码来源:RTEScraper.py

示例6: SetProxy

def SetProxy( proxytype, host, port, username = None, password = None ):
    
    if proxytype == 'http': proxytype = socks.PROXY_TYPE_HTTP
    elif proxytype == 'socks4': proxytype = socks.PROXY_TYPE_SOCKS4
    elif proxytype == 'socks5': proxytype = socks.PROXY_TYPE_SOCKS5
    
    socks.setdefaultproxy( proxy_type = proxytype, addr = host, port = port, username = username, password = password )
    
    socks.wrapmodule( httplib )
开发者ID:Stonedestroyer,项目名称:hydrus,代码行数:9,代码来源:ClientNetworking.py

示例7: socks_activate

	def socks_activate(self,socks_a):
		try:
			socks_raw = socks_a.strip().split(',')
			socks_active = {'ip':socks_raw[0],'port':int(socks_raw[1]),'hostname':socket.gethostbyaddr(socks_raw[0]),'username':socks_raw[3],'password':socks_raw[4]}
			socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, addr=socks_active['ip'], port=socks_active['port'],username=socks_active['username'],password=socks_active['password'])
			socks.wrapmodule(smtplib)
			
			result = (socks_active['hostname'][0],socks_active['ip'])
			# print type(result)
			return result
		except:
			return False
开发者ID:makarowdmitry,项目名称:mailer,代码行数:12,代码来源:mailerbears.py

示例8: get_authenticated_service

def get_authenticated_service():
    """ Create youtube oauth2 connection """
    # make credentials with refresh_token auth
    credentials = AccessTokenCredentials(access_token=get_auth_code(), user_agent='insta-python/1.0')
    # create httplib proxy connection
    if settings.USE_PROXY:
        import socks
        # set socks proxy to ssh tunnel
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 1080)
        # wrap httplib via proxy
        socks.wrapmodule(httplib2)
    # create connection to youtube api
    return build(
        settings.YOUTUBE_API_SERVICE_NAME, settings.YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http()))
开发者ID:underground-maze,项目名称:insta-map,代码行数:14,代码来源:youtube.py

示例9: get

    def get(self, parts, data=None):
        """
        General API call (do not use it directly!)
        """

        #
        # Constructing request path
        #

        callurl = self.url + "/".join(urllib2.quote(p) for p in parts)

        #
        # Constructing data payload
        #

        sdata = None
        if data != None:
            sdata = json.dumps(data)

        #
        # Do the query and respond
        #

        self.dprint(callurl, "with payload", sdata)

        # maybe change it here
        if self.use_proxy:
            socks.wrapmodule(urllib2)
        resp = urllib2.urlopen(callurl, sdata)

        has_getcode = "getcode" in dir(resp)
        if self.debug:
            if has_getcode:
                self.dprint("Response", resp.getcode(), " ".join(str(resp.info()).split("\r\n")))
            else:
                self.dprint("Response", " ".join(str(resp.info()).split("\r\n")))

        if not has_getcode or resp.getcode() == 200:
            rdata = resp.read()
            if re.search("json", resp.info().gettype()):
                try:
                    return json.loads(rdata)
                except TypeError, e:
                    self.dprint(e)
                    return rdata
            else:
                return rdata
开发者ID:mrodozov,项目名称:RPCNoiseToolChain,代码行数:47,代码来源:rrapi.py

示例10: anon_identity

def anon_identity():
    """This function is a example how to use scrape_identity() anonymously
       through TOR. Used like that, you don't have to worry that your generated
       identity is matched to your IP address and therefore to your real identity.
       
    """
    
    # Set up a socks socket. You might want to fire up your local TOR PROXY, before
    # using this function.
    # Just download TOR here https://www.torproject.org/ and then start tor.
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,'127.0.0.1', 9050)
    socks.wrapmodule(urllib.request)
    
    id = scrape_identity()
    print('[+] Generated a random and anonymous identity:')
    for e in id:
        print('\t{0:.<20}{1}'.format(e[0], e[1]))
开发者ID:NikolaiT,项目名称:anonymous_identity,代码行数:17,代码来源:identity_generator.py

示例11: __init__

 def __init__(self, server, sender, password, http_proxy_addr, http_proxy_port):
   socks.setdefaultproxy(socks.PROXY_TYPE_HTTP, http_proxy_addr, int(http_proxy_port))
   socks.wrapmodule(smtplib)
   self.server = server
   self.sender = sender
   self.password = password 
   try:
     self.smtpObj = smtplib.SMTP(server, 587)
     self.smtpObj.ehlo()
     self.smtpObj.starttls()
     self.smtpObj.login(self.sender, self.password)
   except smtplib.SMTPException:
     logger.error("Unable to login to email server " + self.server + " with [username, password] = [" + self.sender + "," + self.password + "]" + ":" + traceback.format_exc())
     raise Exception("Unable to login to email server " + self.server + " with [username, password] = [" + self.sender + "," + self.password + "]" + ":" + traceback.format_exc()) 
   except Exception:
     logger.error("Unable to connect to server : " + server + ":" + traceback.format_exc())
     raise Exception("Unable to connect to server : " + server + ":" + traceback.format_exc())
开发者ID:devendermishrajio,项目名称:AWSS3ConfigManager,代码行数:17,代码来源:mailServer.py

示例12: start

def start():
   global reactor
   global loop

   if ircconf['socks']['enabled']:
      socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ircconf['socks']['host'], ircconf['socks']['port'])
      socks.wrapmodule(irc.client)

   reactor = irc.client.Reactor()
   c = reactor.server().connect( ircconf['server'],
                                 ircconf['port'],
                                 ircconf['nick'],
                                 password=ircconf['passwd'],
                                 connect_factory=irc.connection.Factory())

   reactor.add_global_handler("pubmsg", on_pubmsg)
   loop = renpy.display.layout.DynamicDisplayable(event_loop, reactor)
   renpy.show("loop", what=loop)
开发者ID:FrobtheBuilder,项目名称:vIRC,代码行数:18,代码来源:main.py

示例13: Enable

 def Enable(self):
     self.urllib2_socket = None
     self.httplib_socket = None
     
     log = sys.modules[u"__main__"].log
     
     try:
         log(u"Using proxy: type %i rdns: %i server: %s port: %s user: %s pass: %s" % (self.type, self.dns, self.server, self.port, u"***", u"***") )
 
         self.urllib2_socket = urllib2.socket.socket 
         self.httplib_socket = httplib.socket.socket
          
         socks.setdefaultproxy(self.type, self.server, self.port, self.dns, self.user, self.password)
         socks.wrapmodule(urllib2)
         socks.wrapmodule(httplib)
     except ( Exception ) as exception:
         log(u"Error processing proxy settings", xbmc.LOGERROR)
         log(u"Exception: " + exception.me, xbmc.LOGERROR)
开发者ID:Lusephur,项目名称:plugin-video-irishtv,代码行数:18,代码来源:proxyconfig.py

示例14: simulateFTPSession

def simulateFTPSession(username, password, ftpHost):
    try:
        # We use socksipy to wrap the ftplib to Tor, so the connection actually goes through the Tor network
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
        socks.wrapmodule(ftplib)
        ftp = ftplib.FTP(timeout=60)
        # Connection and login
        ftp.connect(ftpHost, 21)
        ftp.timeout = 30
        ftp.login(username, password)
        # Some fancy commands FileZilla normally sends to servers
        print ftp.sendcmd("SYST")
        print ftp.sendcmd("FEAT")
        print ftp.pwd()
        # Okay, let's get the content of the main directory
        listLines = []
        ftp.dir(listLines.append)
        filenames = []
        for listLine in listLines:
            filenames.append(getFTPFileName(listLine))
        filenames = removeBaitFiles(filenames)
        if len(filenames) > 0:
            # Chose one of the filenames, if the server doesnt consist only of bait files
            filename = random.choice(filenames)
            # Let's wait a little, so the session doesn't look that automated
            waitTime = (random.random() * 20)
            print waitTime
            time.sleep(waitTime)
            # So let's download that file
            print ftp.sendcmd("MDTM " + filename)
            ftp.retrbinary('RETR ' + filename, callbackerDummy)
        # Let's wait a little, so the session doesn't look that automated
        waitTime = (random.random() * 30)
        print waitTime
        time.sleep(waitTime)
        print ftp.quit()
    except Exception:
        raise
    finally:
        try:
            ftp.close()
        except Exception:
            pass
开发者ID:mmulazzani,项目名称:HoneyConnector,代码行数:43,代码来源:ClientMain.py

示例15: __init__

        def __init__(self, timeout, proxy=None, cacert=None, sessions=False):
#            httplib2.debuglevel=4 
            kwargs = {}
            if proxy:
                import socks
                
                socks.setdefaultproxy(socks.PROXY_TYPE_HTTP,proxy['proxy_host'], int(proxy['proxy_port']))
                socks.wrapmodule(httplib2)
                
                kwargs['proxy_info'] = httplib2.ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host=proxy['proxy_host'], proxy_port=int(proxy['proxy_port']))
                
                log.info("using proxy %s" % proxy)

            # set optional parameters according supported httplib2 version
            if httplib2.__version__ >= '0.3.0':
                kwargs['timeout'] = timeout
            if httplib2.__version__ >= '0.7.0':
                kwargs['disable_ssl_certificate_validation'] = cacert is None
                kwargs['ca_certs'] = cacert
            httplib2.Http.__init__(self, **kwargs)
开发者ID:lea-n,项目名称:pysimplesoap,代码行数:20,代码来源:transport.py


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