python绝技——UNIX口令破解机和zip文件口令破解机

1.UNIX口令破解机。
使用python自带的标准库crypt,我们需要使用UNIX计算口令hash的crypt()算法。当我们要计算一个UNIX口令的hash,只需要调用crypt.crypt(),并将口令和salt作为参数传递给它。该函数会以字符串形式返回口令的hash。如图: 在这里插入图片描述
我们将口令"toor"与salt“HX”传递给函数。该函数返回口令的hash——字符串“HXYVTCRlS8dMQ”。成功!下面开始编写代码!

#!/usr/bin/python
#coding=utf-8
import crypt
 
def testPass(cryptPass):
	salt = cryptPass[0:2]
 
	dictFile = open('dictionary.txt','r')
 
	for word in dictFile.readlines():
		word = word.strip('\n')
		cryptWord = crypt.crypt(word,salt)
		if cryptWord == cryptPass:
			print '[+] Found Password: ' + word + "\n"
			return
	print '[-] Password not Found.\n'
	return
def main():
	passFile = open('passwords.txt')
	for line in passFile.readlines():
		if ":" in line:
			user = line.split(':')[0]
			cryptPass = line.split(':')[1].strip(' ')
			print '[*] Cracking Password For : ' + user
			testPass(cryptPass)
 
if __name__ == '__main__':
	main()

我们创建了两个函数:main和testpass。main函数打开加密的口令文件“password.txt”,并逐行读取口令文件中的内容。每一行中的用户名和口令hash分开。对每个口令hash,mian函数都调用testPass()函数,尝试用字典破解它。testPass()函数会以参数的形式获得加密的口令hash,并在找到的密码或者搜索字典失败。该函数首先将加密的口令hash的前两个字符视为salt,并提取出来。然后打开字典中的每一个单词并计算hash,如果计算结果和口令hash匹配,就打印找到密码,并返回它。否则返回没找到。
下图是我们创建的password.txt和dictionary.txt文件示例:
在这里插入图片描述
在这里插入图片描述
测试结果:
在这里插入图片描述
2.zip文件口令破解机。
需要用到库zipfile中的extractall()方法。我创建了一个1.zip文件密码设为123456用来测试代码,当然我们还得创建一个包含正确密码的字典文件!

#!/usr/bin/python
#coding:utf-8
import zipfile
import optparse
from threading import Thread
def extractFile(zFile,password):
    try:
        zFile.extractall(pwd = password)
        print('[+] Found password ' + password + '\n')
    except:
        pass
def main():
    parser = optparse.OptionParser("usage%prog " +\
	"-f <zipfile> -d <dictionary>")
    parser.add_option('-f', dest='zname', type='string',\
	help='specify zip file')
    parser.add_option('-d', dest='dname', type='string',\
	help='specify dictionary file')
    (options,args) = parser.parse_args()
    if (options.zname == None) | (options.dname == None):
        print parser.usage
        exit(0)
    else:
        zname = options.zname
        dname = options.dname
    zFile = zipfile.ZipFile(zname)
    passFile = open(dname)
    for line in passFile.readlines():
        password = line.strip('\n')
        t = Thread(target=extractFile, args=(zFile, password))
        t.start()
if __name__ == '__main__':
    main()

我们把使用线程操作提高代码性能。这样可以同时测试多个口令,对字典中的每个单词,我们都会生成一个新线程去测试它。我们还加入能让用户指定Zip文件的文件名和字典文件名。为了实现这个功能我们使用了optparse库。下面是测试结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40909772/article/details/86585948
今日推荐