首页 > 代码库 > python多进程编程

python多进程编程

最近开始学习PYTHON编程语言,详细参照《python绝技运用Python成为顶级黑客》。在学习过程第一章节中,编写破解LINUX shadow文件时,想利用多线程加快破解速度。主机运行环境为WINDOWS下的VM WORKSTATION上的一台虚拟机,运行多线程代码后并无任何速度上的提升,并且经常伴随输出混乱,不知所以然。故还是利用多进程编写了一个简单的脚本文件,代码如下:

import crypt
import multiprocessing
import time
import sys
def check(passwd):
        cryptWord=crypt.crypt(passwd.strip(‘\n‘),salt.strip(‘\n‘))
        if cryptWord==linuxWord:
                print "password is : "+passwd
                print "harked,time now is :"+currtime()
        else:
                pass

def worker(q):
        while not q.empty():
                passwd =q.get()
                try:
                        check(passwd)
                finally:
                        q.task_done()

def currtime():
        return time.ctime()

def txtToArray(DesFilePath):
        desDic=open(DesFilePath,‘r‘)
        passwdlist=[]
        for line in desDic.readlines():
                passwdlist.append(line)
        return passwdlist

if __name__==‘__main__‘:
        global salt,linuxWord
        print "start time is :"+currtime()
        q=multiprocessing.JoinableQueue()
        linuxWord="$6$9CfIODlW$c34lcX4eYVCD9Kyer3kQLcM6o8Q7uryUroT/K0WVSnnqxtGbPJGDRGymJy4gVMnYgLUjc1J5wVEkrm/jxsQ.i"
        salt="$6$9CfIODl$"
        DesFilePath="/script/1/1.15/password.txt"
        passwdlist=txtToArray(DesFilePath)
        map(q.put,passwdlist)
        jobs=[multiprocessing.Process(target=worker,args=(q,)) for i in xrange(10)]
        map(lambda x:x.start(),jobs)
        q.join()
        print "end time is :"+currtime()


运行效率比多线程要快很多

python多进程编程