之前一直是用的github上別人爬取fofa的腳本,前兩天用的時候只能爬取第一頁的鏈接了,猜測是fofa修改了一部分規則(或者是我不小心刪除了一部分文件導致不能正常運行了)
於是重新寫了一下爬取fofa的代碼,寫的不好:(
因為fofa的登錄界面是https://i.nosec.org/login?service=https%3A%2F%2Ffofa.so%2Fusers%2Fservice

FOFA的登錄跟一般網站登錄不同,在nosec登錄成功后,只擁有nosec的cookie,並沒有fofa的cookie,所以訪問fofa還是未登錄狀態,需要再訪問https://fofa.so/users/sign_in才會生成fofa的cookie。
然后我就換了一種方式,手動添加_fofapro_ars_session來進行登錄,fofapro_ars_session在我們登錄fofa之后使用F12可以查看,這一步比較麻煩
添加了對應的session之后,我們對輸入內容進行base64編碼,因為當我們在fofa網站進行搜索的時候,網站也是將我們輸入的內容進行base64編碼然后進行搜索的
接着解析頁面獲取相應鏈接,持續找到下一頁即可。
需要注意的是,因為fofa也有防止快速爬取的機制,所以我們在爬取的時候要設置一點延時,防止抓取到的IP地址有漏掉的。
在檢索到了搜索的內容之后,首先顯示該搜索對象有多少頁,爬取的頁數也是由輸入者自己決定。
代碼如下:(有一個漂亮的字符畫大LOGO)
# -*- coding:utf-8 -*-
import requests
from lxml import etree
import base64
import re
import time
cookie = ''
def logo():
print('''
/$$$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$
| $$_____//$$__ $$| $$_____//$$__ $$
| $$ | $$ \ $$| $$ | $$ \ $$
| $$$$$ | $$ | $$| $$$$$ | $$$$$$$$
| $$__/ | $$ | $$| $$__/ | $$__ $$
| $$ | $$ | $$| $$ | $$ | $$
| $$ | $$$$$$/| $$ | $$ | $$
|__/ \______/ |__/ |__/ |__/
/$$$$$$ /$$ /$$
/$$__ $$ |__/ | $$
| $$ \__/ /$$$$$$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$
| $$$$$$ /$$__ $$| $$ /$$__ $$ /$$__ $$ /$$__ $$
\____ $$| $$ \ $$| $$| $$ | $$| $$$$$$$$| $$ \__/
/$$ \ $$| $$ | $$| $$| $$ | $$| $$_____/| $$
| $$$$$$/| $$$$$$$/| $$| $$$$$$$| $$$$$$$| $$
\______/ | $$____/ |__/ \_______/ \_______/|__/
| $$
| $$
|__/
version:1.0
''')
def spider():
header = {
"Connection": "keep-alive",
"Cookie": "_fofapro_ars_session=" + cookie,
}
search = input('please input your key: \n')
searchbs64 = (str(base64.b64encode(search.encode('utf-8')), 'utf-8'))
print("spider website is :https://fofa.so/result?&qbase64=" + searchbs64)
html = requests.get(url="https://fofa.so/result?&qbase64=" + searchbs64, headers=header).text
pagenum = re.findall('>(\d*)</a> <a class="next_page" rel="next"', html)
print("have page: "+pagenum[0])
stop_page=input("please input stop page: \n")
#print(stop_page)
doc = open("hello_world.txt", "a+")
for i in range(1,int(pagenum[0])):
print("Now write " + str(i) + " page")
pageurl = requests.get('https://fofa.so/result?page=' + str(i) + '&qbase64=' + searchbs64, headers=header)
tree = etree.HTML(pageurl.text)
urllist=tree.xpath('//div[@class="list_mod_t"]//a[@target="_blank"]/@href')
for j in urllist:
#print(j)
doc.write(j+"\n")
if i==int(stop_page):
break
time.sleep(10)
doc.close()
print("OK,Spider is End .")
def start():
print("Hello!My name is Spring bird.First you should make sure _fofapro_ars_session!!!")
print("And time sleep is 10s")
def main():
logo()
start()
spider()
if __name__ == '__main__':
main()
Github鏈接:https://github.com/Cl0udG0d/Fofa-script
我設置的time.sleep()延時是10秒,可以根據自己的需求進行修改,以及,雖然在代碼里面進行了base64解碼,但是有的時候總會出現編碼問題而導致搜索不到想要的結果,pagenum[0]等於0的情況,如果修改關鍵字還是不行的話,可以自己在fofa網站里面查了之后,在url中將base64之后的搜索關鍵字替換成代碼里面的searchbs64,這樣就必然能夠搜索到了,這些不足的地方在下次修改的時候進行改進吧,奧利給。
