Python

python߳͸еӦ

ֺ+ ߣiϰ Դת 2017-03-09 13:54 Ҫ( )

ǰ pythonżѧԣǿĵڱ°빦 죬̸̸python߳ ͸ еӦãģǽдһcδ......

ǰ
pythonżѧԣǿĵڱ°빦죬̸̸python߳͸еӦãģǽдһcδɨűԼһpython汾Ķ߳--Ŀ¼ɨ蹤

һpython ߳
python߳мд
1. threadģ
pythonһ߳ģ飬Сűã覴ã粻ȶ߳ÿ

·һcδɨűűiadoʦҲ
Ŷ
˼룺һipַ֣ȡcΣ̵߳ping -c 2 ip ݷصϢжǷ
demo ping_thread.py:

[Python] ı鿴 ƴ
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'''
Created on 2017-2-27
 
@author: xiaoye
'''
#coding: utf-8
import thread
import time
from subprocess import Popen,PIPE
 
def scan_ip(ip):
    process = Popen('ping -c 2 ' + ip, stdin=PIPE, stdout=PIPE, shell=True)
    data = process.stdout.read()
    if 'ttl' in data:
        print '%s is live ,now time is %s' % (ip, time.strftime('%H:%M:%S'))
     
if __name__ == '__main__':
    #scan_ip('111.13.147.229')
    ips = raw_input()
    ip_header = '.'.join(ips.split('.')[:3])
    for i in range(1,255):
        ip = ip_header + '.' + str(i)
        #print ip
        thread.start_new_thread(scan_ip, (ip,))
        time.sleep(0.1)

 
ٶȻУȶһ

threadģ飬ڣ

[Python] ı鿴 ƴ
?
1
2
thread.start_new_thread(scan_ip, (ip,))
        time.sleep(0.1)

scan_ipҪִеĺ(ip,)ǴIJǵsleepһ

2.threadingģ÷
demo:

[Python] ı鿴 ƴ
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'''
Created on 2017-2-28
@author: xiaoye
'''
#coding: utf-8
import threading
import time
 
def test(th):
    print 'i am doing %s %s' % (th, time.strftime('%H:%M:%S'))
     
def main():
    thread = []
    keys = ['movie_th','swim_th','listen_th','learn_th','movie_th','swim_th','listen_th','learn_th','movie_th','swim_th','listen_th','learn_th','movie_th','swim_th','listen_th','learn_th']
    thread_count = len(keys)
    #print thread_count
    for i in range(thread_count):
        t = threading.Thread(target=test, args=(keys[i],))
        thread.append(t)
    for i in range(thread_count):
        thread[i].start()
    for i in range(thread_count):
        thread[i].join()
 
if __name__ == '__main__':
    main()



Կͬʱеģthreading.Threadģһ÷

[Python] ı鿴 ƴ
?
1
2
3
4
5
6
7
for i in range(thread_count):
        t = threading.Thread(target=test, args=(keys[i],))
        thread.append(t)
    for i in range(thread_count):
        thread[i].start()
    for i in range(thread_count):
        thread[i].join()

ģʽ1.һб̣߳start()ִб̣߳join()ȴ

ģʽ1ģʽ2
Ȼģʽ2Ǵthreading.Thread̳һclassдrunʵֶ߳runҲǷdzõд
demo:

[Python] ı鿴 ƴ
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# -*- coding: utf-8 -*-
import threading
 
class T(threading.Thread):
 
    def __init__(self):
        threading.Thread.__init__(self)
 
    def run(self):                    #̳,threading.Thread, дrun, runstart()Զִ
        print 'i love you'
 
 
def main():
    thread = []
    for i in range(10):
      thread.append(T())
    for i in thread:
        i.start()
    for i in thread:
        i.join()
 
if __name__ == '__main__':
    main()





̼߳ػ
QueueDZ̼߳ݰȫĺѡйQueueҿаٶ÷ҷһ㾭õģ


Queue.qsize() ضеĴС
Queue.empty() ΪգTrue,֮False
Queue.full() ˣTrue,֮False
Queue.full maxsize СӦ
Queue.get([block[, timeout]]) ȡУtimeoutȴʱ
Queue.get_nowait() ൱Queue.get(False)
Queue.put(item) дУtimeoutȴʱ
Queue.put_nowait(item) ൱Queue.put(item, False)
Queue.task_done() һ֮Queue.task_done() ѾɵĶзһź
Queue.join() ʵζŵȵΪգִбIJ


߳threading.Thread+Queueʵ͸Թд
űų
1.߳cδɨ裺

[Python] ı鿴 ƴ
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'''
Created on 2017-2-28
@author: xiaoye
'''
#coding: utf-8
import time
import sys
import threading
import Queue
from subprocess import Popen,PIPE
 
 
class Quethread(threading.Thread):
    def __init__(self, que):
        threading.Thread.__init__(self)
        self._que = que
     
    def run(self):
        while not self._que.empty():
            ip = self._que.get()
            process = Popen('ping -c 2 ' + ip, stdin=PIPE, stdout=PIPE, shell=True)
            data = process.stdout.read()
            if 'ttl' in data:
                sys.stdout.write('%s is live %s\n' % (ip, time.strftime('%H:%M:%S')))
     
     
def main():
    que = Queue.Queue()
    ips = raw_input()
    thread = []
    thread_count = 200
    ip_head = '.'.join(ips.split('.')[:3])
    #print ip_head
    for i in range(1, 255):
        que.put(ip_head + '.' + str(i))
    '''for i in range(1,255):
        print que.get()'''
     
    for i in range(thread_count):
        thread.append(Quethread(que))
         
    for i in thread:
        i.start()
         
    for i in thread:
        i.join()
         
     
if __name__ == '__main__':
    main()

ubuntuгɹwinҪ޸Popenȣͼ

ٶȺܿ죬ȶԽǿ
https://github.com/xiaoyecent/ping_threading_Queue

2.py߳--Ŀ¼ɨ--֧Զֵ䡢ļλԼԶ߳

[Python] ı鿴 ƴ
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'''
@author: xiaoye
'''
#coding: utf-8
import requests
import sys
import threading
#import time
import Queue
from optparse import OptionParser
 
reload(sys)
sys.setdefaultencoding('utf8')
 
class Doscan(threading.Thread):
    def __init__(self, que):
        threading.Thread.__init__(self)
        self._que = que
         
    def run(self):
        while not self._que.empty():
            d = self._que.get()
            try:
                r = requests.get(url + d, headers=headers, timeout=3)
                sys.stdout.write(d + ' is scan  status:' + str(r.status_code) + '\n')
                if r.status_code == 200:
                    with open(option.outfile, 'a') as f:
                        f.write(url + d + '\n')
            except:
                pass
     
def main():
    thread = []
    thread_count = option.threadcount
    que = Queue.Queue()
     
    with open(option.dictname, 'r') as f:
        for d in f.readlines():
            d = d.strip('\n')
            que.put(d)
     
    for i in range(thread_count):
        thread.append(Doscan(que))
     
    for i in thread:
        i.start()
     
    for i in thread:
        i.join()
         
if __name__ == '__main__':
    parse = OptionParser()
    parse.add_option('-u', '--url', dest='input_url', type='string', help='the url you wan to scan dir')
    parse.add_option('-o', '--out', dest='outfile', type='string', help='output filename', default='result.txt')
    parse.add_option('-s', '--speed', dest='threadcount', type='int', default=60, help='the thread_count')
    parse.add_option('-d', '--dict', dest='dictname', type='string', help='dict filename')
    (option, args) = parse.parse_args()
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    url = option.input_url
    main()
            


[Python] ı鿴 ƴ
?
01
02
03
04
05
06
07
08
09
10
11
12
Usage: scan_dir.py [options]
 
Options:
  -h, --help            show this help message and exit
  -u INPUT_URL, --url=INPUT_URL
                        the url you wan to scan dir
  -o OUTFILE, --out=OUTFILE
                        output filename
  -s THREADCOUNT, --speed=THREADCOUNT
                        the thread_count
  -d DICTNAME, --dict=DICTNAME
                        dict filename


÷

ٸӣ
-u http://localhost -s 30 -d d://PHP.txt -o d://ichunqiu.txt





ٶȡ߳Ĭ60ʵʻ
Դ룺https://github.com/xiaoyecent/scan_dir

ġܽ
̼߳Ӷʵ̼߳ݱǺܺõĴ䣬threading.Thread+Queue÷ϣܹգ⣬̳
threading.Threadд࣬дrunʵ̵ֶ߳дҲֵý

: 's Blog-ע簲ȫ http://blog.icxun.cn/Python/590.html

1.վѭҵ淶κתصĸȷעߺԴ2.վԭ£תʱעߺԴԭΪǽ׷Σ3.ͶܻᾭDZ༭޸Ļ򲹳䡣

ѵ
ʱδ۹~