MENU

Python 识别简单验证码

July 15, 2016 • Read: 3292 • CTF

最近做题的时候碰到好几道 WEB 都需要验证码识别,如果是爆破,那么 PKAV 的 Http Fuzzer 就可以了,但如果题目更变态一点,需要做复杂的操作,那个简单的 Fuzzer 就没办法了,还是得自己写脚本。

依赖

识别验证码,肯定需要图像库 PIL ,还需要一个可以做简单识别的库 pytesseract ,毕竟只是做个题,总不能自己训练一个出来,没那功夫。

再吐槽一下 windows 这个坑,pip 没法安装 PIL ,下了二进制包安,用的时候各种报错,网上说还需要 32 位,64 位一起装。。。

还是用 Kali 吧,好歹 PIL 库是已经有的。

pip install pytesseract

结果用的时候又发现报错,查了一下说是 pytesseract 依赖一个 tesseract-ocr 的东西。。。好烦。。。

tesseract-ocr

幸好 Linux 可以直接装,不用编译。

apt-cache search tesseract
apt-get install tesseract-ocr

简单使用

为了测试,我随便找了个验证码图片放到本地,写了两行测试脚本。

# coding=utf-8
from PIL import Image
import pytesseract

im = Image.open('vcode.png')
vcode = pytesseract.image_to_string(im)
print vcode

找一处在线的验证码识别一下看看准确率。

# coding=utf-8
from PIL import Image
import pytesseract
import requests

for i in range(10):
    re = requests.get('http://lab1.xseclab.com/vcode7_f7947d56f22133dbc85dda4f28530268/vcode.php')
    open('vcode.png', 'wb').write(re.content)
    im = Image.open('vcode.png')
    vcode = pytesseract.image_to_string(im)
    print vcode
╭─root@kali  ~/Desktop/image  
╰─$ python shibie.py
445 9
7433
8603
7841
9530
2 144
08 72
4332
1703
5037

可以看到,识别率还凑合,但是中间经常会多出一个空格,有几个数字还错了。。参考网上的例子改进一下。

# coding=utf-8
from PIL import Image
import pytesseract
import requests


for i in range(10):
    re = requests.get('http://lab1.xseclab.com/vcode7_f7947d56f22133dbc85dda4f28530268/vcode.php')
    open('vcode.png', 'wb').write(re.content)
    im = Image.open('vcode.png')
    imgry = im.convert('L')

    threshold = 140
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    out = imgry.point(table, '1')
    vcode = pytesseract.image_to_string(im)
    print vcode
╭─root@kali  ~/Desktop/image  
╰─$ python shibie.py                                   
0378
1154

0316
7402
2269
0493
8°90
9602
4925

只能算差强人意吧。。。也就这个精度了。

Last Modified: February 14, 2017
Archives QR Code
QR Code for this page
Tipping QR Code