Advertisement
parkdream1

test.py

Jul 5th, 2013
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.03 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # import thư viện
  3. import socks
  4. import httplib
  5. import urllib2
  6. import sys
  7. import re
  8. import socket
  9. import time
  10. import threading
  11. from configobj import ConfigObj
  12. # Tên File config
  13. filename = 'X-Proxy.config'
  14. config = ConfigObj(filename)
  15. # Load config từ file config
  16.  
  17. try:
  18.     SetTimeOut = config['SetTimeOut'] # set timeout Ex : True/False
  19.     TimeOut = config['TimeOut'] # set timeout Ex : 15
  20.     SaveOutput = config['SaveOutput'] # có lưu file output không Ex : True/False
  21.     OutPutFile = config['OutPutFile'] # tên file output
  22.     DebugMode = config['DebugMode'] # hiện thị thông tin debug
  23.     ProxyFile = config['ProxyFile'] # tên file proxy sẽ load vào
  24.     Url_TestProxy = config['Url_TestProxy'] # url test proxy
  25.     User_Agent = config['User_Agent']
  26.     #print 'Loaded Config File : ' + filename
  27.     if DebugMode =='True':
  28.         print 'Config Info :\n'
  29.         print "SetTimeOut : " + SetTimeOut
  30.         print "TimeOut : " + TimeOut
  31.         print "SaveOutput : " + SaveOutput
  32.         print "OutPutFile : " + OutPutFile
  33.         print "DebugMode : " + DebugMode
  34.         print "ProxyFile : " + ProxyFile
  35.         print "Url_TestProxy : " + Url_TestProxy
  36.         print 'User_Agent : ' + User_Agent + '\n'
  37. except:
  38.     print 'Load File : ' + filename + ' error'
  39.     print 'Exit'
  40.     sys.exit(1)
  41.    
  42. class SocksiPyConnection(httplib.HTTPConnection):
  43.     def __init__(self, proxytype, proxyaddr, proxyport = None, rdns = True, username = None, password = None, *args, **kwargs):
  44.         self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password)
  45.         httplib.HTTPConnection.__init__(self, *args, **kwargs)
  46.  
  47.     def connect(self):
  48.         self.sock = socks.socksocket()
  49.         self.sock.setproxy(*self.proxyargs)
  50.         if isinstance(self.timeout, float):
  51.             self.sock.settimeout(self.timeout)
  52.         self.sock.connect((self.host, self.port))
  53.            
  54. class SocksiPyHandler(urllib2.HTTPHandler):
  55.     def __init__(self, *args, **kwargs):
  56.         self.args = args
  57.         self.kw = kwargs
  58.         urllib2.HTTPHandler.__init__(self)
  59.  
  60.     def http_open(self, req):
  61.         def build(host, port=None, strict=None, timeout=0):    
  62.             conn = SocksiPyConnection(*self.args, host=host, port=port, strict=strict, timeout=timeout, **self.kw)
  63.             return conn
  64.         return self.do_open(build, req)
  65.  
  66. def GetProxyList():
  67.     try:
  68.         print 'Load Proxy File : ' + ProxyFile
  69.         proxy_list = []
  70.         with open(ProxyFile) as f:
  71.             for line in f.readlines():
  72.                 proxy = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\:(?:[\d]{1,5})',line)
  73.                 if proxy:
  74.                     if any(proxy[0] in item for item in proxy_list)==False:
  75.                         proxy_list.append(proxy[0])
  76.                         if DebugMode =='True':
  77.                             print proxy[0] + ' append To Proxy List'
  78.                 else:
  79.                     continue
  80.         lenght = str(len(proxy_list))
  81.         if lenght<1:
  82.             print 'Proxy not found !'
  83.             sys.exit(1)
  84.         elif lenght==1:
  85.             print 'Proxy: 1'
  86.         else:
  87.              print 'Proxies: ' + lenght
  88.          
  89.         return proxy_list
  90.     except:
  91.         print 'Load Proxy File ' + ProxyFile + ' Error'
  92.         sys.exit(1)
  93.        
  94. def CheckProxy(proxy):
  95.     try:
  96.         s = socks.socksocket()
  97.         s.setproxy(socks.PROXY_TYPE_SOCKS5, proxy.split(':')[0], int(proxy.split(':')[1]))
  98.        
  99.         DATA = ('GET / HTTP/1.1\r\n' +
  100.                 'Host: %s\r\n' +
  101.                 'User-Agent: %s\r\n' +
  102.                 'Connection: close\r\n' +
  103.                 '\r\n') % (Url_TestProxy,User_Agent)
  104.         if DebugMode =='True': print 'Headers : ' + DATA
  105.         s.connect((Url_TestProxy, 80))
  106.         s.send(DATA)
  107.         buf = s.recv(8)
  108.         html = ''
  109.         while len(buf):
  110.             html += buf
  111.             buf = s.recv(16)
  112.             if DebugMode =='True': print 'Recv : ' + html
  113.             if html.find('HTTP/1.1')>=0:
  114.                 s.close()
  115.                 return 1
  116.                 break
  117.             s.close()
  118.     except:
  119.         return 0
  120. def main(proxy):
  121.     print 'Check Proxy ' + proxy + '\n'
  122.     if CheckProxy(proxy) == 1:
  123.         if SaveOutput == 'True':
  124.             print 'Proxy ' + proxy + ' Live'
  125.             open(OutPutFile, 'a').write('%s\n'%proxy)
  126.             if DebugMode =='True': print proxy + ' writed to ' + OutPutFile
  127.             sys.exit(1)
  128.     else:
  129.         print 'Proxy ' + proxy + ' Die'
  130.         sys.exit(1)
  131. if __name__ == '__main__':
  132.     start_time = time.clock()
  133.     NumberThread = 5
  134.     i = 0
  135.     j = 0
  136.     Start_NumberThread = 0
  137.     End_NumberThread = NumberThread
  138.     proxy_list = GetProxyList()
  139.     if SetTimeOut=='True':
  140.         socket.setdefaulttimeout(float(TimeOut))
  141.         if DebugMode =='True': print 'Used TimeOut ' + str(TimeOut)
  142.     while i < len(proxy_list):
  143.         if NumberThread < len(proxy_list):
  144.             for j in (Start_NumberThread, End_NumberThread):
  145.                 proxy = proxy_list[j]
  146.                 threads = []
  147.                 thread = threading.Thread(target = main,args = (proxy,))
  148.                 thread.start()
  149.                 threads.append(thread)
  150.             for thread in threads:
  151.                 thread.join()
  152.         else:
  153.             print 'NumberThread = ' + str(NumberThread) + ' > ' + 'Total Proxy = ' + str(len(proxy_list))
  154.         i = i + NumberThread
  155.         j = Start_NumberThread
  156.         Start_NumberThread = i
  157.         End_NumberThread = i + NumberThread - 1
  158.     end_time = time.clock()
  159.     run_time = end_time - start_time
  160.     print 'Time Check : %.2gs' % (run_time)
  161.     open(OutPutFile, 'a').write('Time Check : %.2gs\nTools by parkdream1\n'%(run_time))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement