Я хотел бы проверить бесконечность количества самостоятельно сгенерированных URL-адресов на предмет достоверности и, если допустимо, безопасного тела ответа в файле. URL-адреса выглядят так: https://mydomain.com/ + случайная строка (например, https://mydomain.com/ake3t), и я хочу сгенерировать их, используя алфавит "abcdefghijklmnopqrstuvwxyz0123456789_-", и просто грубой силой опробуйте все возможности.
Я написал скрипт на python, но, поскольку я здесь абсолютный новичок, он был очень медленным! Поскольку мне нужно что-то очень-очень быстрое, я старался использовать скрап, так как думал, что это предназначено именно для такой работы.
Теперь проблема в том, что я не могу выяснить, как динамически генерировать URL-адреса на лету, я не могу генерировать их заранее, поскольку их число не фиксированное.
Может ли кто-нибудь показать мне, как этого добиться, или порекомендовать мне другой инструмент или библиотеку, даже лучше подходящую для этой работы?
UPDATE:
Это сценарий, который я использовал, но я думаю, что он медленный. Что меня больше всего беспокоит, так это то, что становится медленнее, если я использую более одного потока (указанного в threadsNr)
import threading, os
import urllib.request, urllib.parse, urllib.error
threadsNr = 1
dumpFolder = '/tmp/urls/'
charSet = 'abcdefghijklmnopqrstuvwxyz0123456789_-'
Url_pre = 'http://vorratsraum.com/'
Url_post = 'alwaysTheSameTail'
# class that generate the words
class wordGenerator ():
def __init__(self, word, charSet):
self.currentWord = word
self.charSet = charSet
# generate the next word set that word as currentWord and return the word
def nextWord (self):
self.currentWord = self._incWord(self.currentWord)
return self.currentWord
# generate the next word
def _incWord(self, word):
word = str(word) # convert to string
if word == '': # if word is empty
return self.charSet[0] # return first char from the char set
wordLastChar = word[len(word)-1] # get the last char
wordLeftSide = word[0:len(word)-1] # get word without the last char
lastCharPos = self.charSet.find(wordLastChar) # get position of last char in the char set
if (lastCharPos+1) < len(self.charSet): # if position of last char is not at the end of the char set
wordLastChar = self.charSet[lastCharPos+1] # get next char from the char set
else: # it is the last char
wordLastChar = self.charSet[0] # reset last char to have first character from the char set
wordLeftSide = self._incWord(wordLeftSide) # send left site to be increased
return wordLeftSide + wordLastChar # return the next word
class newThread(threading.Thread):
def run(self):
global exitThread
global wordsTried
global newWord
global hashList
while exitThread == False:
part = newWord.nextWord() # generate the next word to try
url = Url_pre + part + Url_post
wordsTried = wordsTried + 1
if wordsTried == 1000: # just for testing how fast it is
exitThread = True
print( 'trying ' + part) # display the word
print( 'At URL ' + url)
try:
req = urllib.request.Request(url)
req.addheaders = [('User-agent', 'Mozilla/5.0')]
resp = urllib.request.urlopen(req)
result = resp.read()
found(part, result)
except urllib.error.URLError as err:
if err.code == 404:
print('Page not found!')
elif err.code == 403:
print('Access denied!')
else:
print('Something happened! Error code', err.code)
except urllib.error.URLError as err:
print('Some other error happened:', err.reason)
resultFile.close()
def found(part, result):
global exitThread
global resultFile
resultFile.write(part +"\n")
if not os.path.isdir(dumpFolder + part):
os.makedirs(dumpFolder + part)
print('Found Part = ' + part)
wordsTried = 0
exitThread = False # flag to kill all threads
newWord = wordGenerator('',charSet); # word generator
if not os.path.isdir(dumpFolder):
os.makedirs(dumpFolder)
resultFile = open(dumpFolder + 'parts.txt','a') # open file for append
for i in range(threadsNr):
newThread().start()