-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
crawler.py
889 lines (595 loc) · 23.1 KB
/
crawler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
"""
Open Crawler 0.0.1
License - MIT ,
An open source crawler/spider
Features :
- Cross Platform
- Easy install
- Related-CLI Tools (includes ,CLI access to tool, not that good search-tool xD, etc)
- Memory efficient [ig]
- Pool Crawling - Use multiple crawlers at same time
- Supports Robot.txt
- MongoDB [DB]
- Language Detection
- 18 + Checks / Offensive Content Check
- Proxies
- Multi Threading
- Url Scanning
- Keyword, Desc And recurring words Logging
Author - Merwin M
"""
from memory_profiler import profile
from collections import Counter
from functools import lru_cache
from bs4 import BeautifulSoup
from langdetect import detect
from mongo_db import *
from rich import print
import urllib.robotparser
import threading
import requests
import signal
import atexit
import random
import json
import time
import sys
import re
import os
"""
######### Crawled Info are stored in Mongo DB as #####
Crawled sites = [
{
"website" : "<website>"
"time" : "<last_crawled_in_epoch_time>",
"mal" : Val/None, # malicious or not
"offn" : Val/None, # 18 +/ Offensive language
"ln" : "<language>",
"keys" : [<meta-keywords>],
"desc" : "<meta-desc>",
"recc" : [<recurring words>]/None,
}
]
"""
## Regex patterns
html_pattern = re.compile(r'<[^>]+>')
url_extract_pattern = "https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)"
url_pattern = "^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$"
url_pattern_0 = "^[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$"
url_extract_pattern_0 = "[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)"
# Config File
config_file = "config.json"
# Load configs from config_file - > json
try:
config_file = open(config_file, "r")
configs = json.loads(config_file.read())
config_file.close()
except:
try:
os.system("python3 config.py") # Re-configures
except:
os.system("python config.py") # Re-configures
config_file = open(config_file, "r")
configs = json.loads(config_file.read())
config_file.close()
## Setting Up Configs
MONGODB_PWD = configs["MONGODB_PWD"]
MONGODB_URI = configs["MONGODB_URI"]
TIMEOUT = configs["TIMEOUT"] # Timeout for reqs
MAX_THREADS = configs["MAX_THREADS"]
bad_words = configs["bad_words"]
USE_PROXIES = configs["USE_PROXIES"]
Scan_Bad_Words = configs["Scan_Bad_Words"]
Scan_Top_Keywords = configs["Scan_Top_Keywords"]
URL_SCAN = configs["URL_SCAN"]
urlscan_key = configs["urlscan_key"]
del configs
## Main Vars
EXIT_FLAG = False
DB = None
ROBOT_SCANS = [] # On Going robot scans
WEBSITE_SCANS = [] # On Going website scans
PROXY_CHECK = False
HTTP = []
HTTPS = []
# Loads bad words / flaged words
file = open(bad_words, "r")
bad_words = file.read()
file.close()
bad_words = tuple(bad_words.split("\n"))
# @lru_cache(maxsize=100)
# def get_robot(domain):
# """
# reads robots.txt
# """
# print(f"[green] [+] Scans - {domain} for restrictions")
# rp = urllib.robotparser.RobotFileParser()
# rp.set_url("http://" + domain + "/robots.txt")
# return rp.can_fetch
def get_top_reccuring(txt):
"""
Gets most reccuring 8 terms from the website html
txt : str
returns : list
"""
split_it = txt.split()
counter = Counter(split_it)
try:
most_occur = counter.most_common(8)
return most_occur
except:
return []
def lang_d(txt):
"""
Scans for bad words/ flaged words.
txt : str
return : int - > score
"""
if not Scan_Bad_Words:
return None
score = 0
for e in bad_words:
try:
x = txt.split(e)
except:
continue
score += len(x)-1
try:
score = round(score/len(txt))
except:
pass
return score
def proxy_checker(proxies, url="https://www.google.com"):
working_proxies = []
proxies = proxies.text.split("\r\n")
if url.startswith("https"):
protocol = "https"
else:
protocol = "http"
proxies.pop()
for proxy in proxies:
try:
response = requests.get(url, proxies={protocol:proxy}, timeout=2)
if response.status_code == 200:
print(f"Proxy {proxy} works! [{len(working_proxies)+1}]")
working_proxies.append(proxy)
else:
pass
except requests.RequestException as e:
pass
return working_proxies
def proxy_checker_(proxies, url="https://www.wired.com/review/klipsch-flexus-core-200/"):
working_proxies = []
proxies = proxies.split("\n")
if url.startswith("https"):
protocol = "https"
else:
protocol = "http"
proxies.pop()
for proxy in proxies:
try:
response = requests.get(url, proxies={protocol:proxy}, timeout=2)
if response.status_code == 200:
print(f"Proxy {proxy} works! [{len(working_proxies)+1}]")
working_proxies.append(proxy)
else:
pass
except requests.RequestException as e:
pass
return working_proxies
def get_proxy():
"""
Gets a free proxy from 'proxyscrape'
returns : dict - > {"http": "<proxy ip:port>"}
"""
global PROXY_CHECK, HTTP, HTTPS
if not PROXY_CHECK:
try:
f = open("found_proxies_http")
f2 = open("found_proxies_https")
res = f.read()
res2 = f2.read()
HTTP = proxy_checker_(res, "http://www.wired.com/review/klipsch-flexus-core-200/")
HTTPS = proxy_checker_(res2)
PROXY_CHECK = True
print(f"[green]Total Number Of HTTP PROXIES FOUND : {len(HTTP)} [/green]")
print(f"[green]Total Number Of HTTPS PROXIES FOUND : {len(HTTPS)} [/green]")
f2.close()
f.close()
except:
pass
if not PROXY_CHECK:
print("We are generating a new proxy list so it would take time... \[this happens when you are using old proxylist/have none]")
res = requests.get("https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all")
res2= requests.get("https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all")
HTTP = proxy_checker(res, "http://google.com")
HTTPS = proxy_checker(res2)
PROXY_CHECK = True
print(f"[green]Total Number Of HTTP PROXIES FOUND : {len(HTTP)} [/green]")
print(f"[green]Total Number Of HTTPS PROXIES FOUND : {len(HTTPS)} [/green]")
f = open("found_proxies_http", "w")
f2 = open("found_proxies_https", "w")
f.write("\n".join(HTTP))
f2.write("\n".join(HTTPS))
f.close()
f2.close()
return {"http" : random.choice(HTTP), "https": random.choice(HTTPS)}
def scan_url(url):
"""
Scans url for malicious stuff , Uses the Urlscan API
url : str
return : int - > score
"""
headers = {'API-Key':urlscan_key,'Content-Type':'application/json'}
data = {"url": url, "visibility": "public"}
r = requests.post('https://urlscan.io/api/v1/scan/',headers=headers, data=json.dumps(data))
print(r.json())
r = "https://urlscan.io/api/v1/result/" + r.json()["uuid"]
for e in range(0,100):
time.sleep(2)
res = requests.get(r, headers)
res = res.json()
try:
if res["status"] == 404:
pass
except:
print(res["verdicts"])
return res["verdicts"]["urlscan"]["score"]
return None
def remove_html(string):
"""
removes html tags
string : str
return : str
"""
return html_pattern.sub('', string)
def handler(SignalNumber, Frame): # for handling SIGINT
safe_exit()
signal.signal(signal.SIGINT, handler) # register handler
def safe_exit(): # safely exits the program
global EXIT_FLAG
print(f"\n\n[blue] [\] Exit Triggered At : {time.time()} [/blue]")
EXIT_FLAG = True
print("[red] EXITED [/red]")
atexit.register(safe_exit) # registers at exit handler
def forced_crawl(website):
"""
Crawl a website forcefully - ignorring the crawl wait list
website : string
"""
# Checks if crawled already , y__ = crawled or not , True/False
z__ = if_crawled(website)
y__ = z__[0]
mal = None
lang_18 = None
lang = None
# Current thread no. as there is no separate threads for crawling, set as 0
th = 0
print(f"[green] [+] Started Crawling : {website} | Thread : {th}[/green]")
proxies = {}
if USE_PROXIES:
proxies = get_proxy()
try:
website_req = requests.get(website, headers = {"user-agent":"open crawler v 0.0.1"}, proxies = proxies, timeout = TIMEOUT)
# checks if content is html or skips
try:
if not "html" in website_req.headers["Content-Type"]:
print(f"[green] [+] Skiped : {website} Because Content type not 'html' | Thread : {th}[/green]")
return 0
except:
return 0
website_txt = website_req.text
if not y__:
save_crawl(website, time.time(), 0,0,0,0,0,0,)
else:
update_crawl(website, time.time(), 0,0,0,0,0,0)
except:
# could be because website is down or the timeout
print(f"[red] [-] Coundn't Crwal : {website} | Thread : {th}[/red]")
if not y__:
save_crawl(website, time.time(), "ERROR OCCURED", 0, 0, 0, 0, 0)
else:
update_crawl(website, time.time(), "ERROR OCCURED", 0, 0, 0, 0, 0)
return 0
try:
lang = detect(website_txt)
except:
lang = "un-dic"
if URL_SCAN:
mal = scan_url(website)
website_txt_ = remove_html(website_txt)
if Scan_Bad_Words:
lang_18 = lang_d(website_txt_)
keywords = []
desc = ""
soup = BeautifulSoup(website_txt, 'html.parser')
for meta in soup.findAll("meta"):
try:
if meta["name"] == "keywords":
keywords = meta["content"]
except:
pass
try:
if meta["name"] == "description":
desc = meta["content"]
except:
pass
del soup
top_r = None
if Scan_Top_Keywords:
top_r = get_top_reccuring(website_txt_)
update_crawl(website, time.time(), mal, lang_18, lang, keywords, desc, top_r)
del mal, lang_18, lang, keywords, desc, top_r
sub_urls = []
for x in re.findall(url_extract_pattern, website_txt):
if re.match(url_pattern, x):
if ".onion" in x:
# skips onion sites
continue
if x[-1] == "/" or x.endswith(".html") or x.split("/")[-1].isalnum():
# tries to filture out not crawlable urls
sub_urls.append(x)
# removes all duplicates
sub_urls = set(sub_urls)
sub_urls = list(sub_urls)
# check for restrictions in robots.txt and filture out the urls found
for sub_url in sub_urls:
if if_waiting(sub_url):
sub_urls.remove(sub_url)
continue
# restricted = robots_txt.disallowed(sub_url, proxies)
# t = sub_url.split("://")[1].split("/")
# t.remove(t[0])
# t_ = ""
# for u in t:
# t_ += "/" + u
# t = t_
# restricted = tuple(restricted)
# for resk in restricted:
# if t.startswith(resk):
# sub_urls.remove(sub_url)
# break
site = sub_url.replace("https://", "")
site = site.replace("http://", "")
domain = site.split("/")[0]
# print(f"[green] [+] Scans - {domain} for restrictions")
rp = urllib.robotparser.RobotFileParser()
rp.set_url("http://" + domain + "/robots.txt")
# a = get_robot(domain)
if not rp.can_fetch("*", sub_url):
sub_urls.remove(sub_url)
# try:
# restricted = get_robots(domain)
# except:
# print(f"[green] [+] Scans - {domain} for restrictions")
# restricted = robots_txt.disallowed(sub_url, proxies)
# save_robots(domain, restricted)
# restricted = tuple(restricted)
# t = sub_url.split("://")[1].split("/")
# t.remove(t[0])
# t_ = ""
# for u in t:
# t_ += "/" + u
# t = t_
# for resk in restricted:
# if t.startswith(resk):
# sub_urls.remove(sub_url)
# break
# check if there is a need of crawling
for e in sub_urls:
z__ = if_crawled(e)
y__ = z__[0]
t__ = z__[1]
if y__:
if t__ < time.time() - 604800 : # Re-Crawls Only After 7
sub_urls.remove(e)
continue
try:
website_req = requests.get(e, headers = {"user-agent":"open crawler v 0.0.1"}, proxies = proxies, timeout = TIMEOUT)
except:
sub_urls.remove(e)
continue
try:
if not "html" in website_req.headers["Content-Type"]:
print(f"[green] [+] Skiped : {e} Because Content type not 'html' | Thread : {th}[/green]")
sub_urls.remove(e)
continue
except:
sub_urls.remove(e)
continue
write_to_wait_list(sub_urls)
del sub_urls
print(f"[green] [+] Crawled : {website} | Thread : {th}[/green]")
## for checking the memory usage uncomment @profile , also uncoment for main()
# @profile
def crawl(th):
global ROBOT_SCANS, WEBSITE_SCANS
time.sleep(th)
if EXIT_FLAG:
return 1
while not EXIT_FLAG:
# gets 10 urls from waitlist
sub_urls = get_wait_list(10)
for website in sub_urls:
if website in WEBSITE_SCANS:
continue
else:
WEBSITE_SCANS.append(website)
website_url = website
website = website["website"]
update = False
# Checks if crawled already , y__ = crawled or not , True/False
z__ = if_crawled(website)
y__ = z__[0]
t__ = z__[1]
if y__:
update = True
if int(time.time()) - int(t__) < 604800: # Re-Crawls Only After 7
print(f"[green] [+] Already Crawled : {website} | Thread : {th}[/green]")
continue
print(f"[green] [+] ReCrawling : {website} | Thread : {th} [/green]")
mal = None
lang_18 = None
lang = None
print(f"[green] [+] Started Crawling : {website} | Thread : {th}[/green]")
proxies = {}
if USE_PROXIES:
proxies = get_proxy()
try:
website_req = requests.get(website, headers = {"user-agent":"open crawler v 0.0.1"}, proxies = proxies, timeout = TIMEOUT)
try:
if not "html" in website_req.headers["Content-Type"]:
# checks if the site responds with html content or skips
print(f"[green] [+] Skiped : {website} Because Content type not 'html' | Thread : {th}[/green]")
continue
except:
continue
website_txt = website_req.text
if not update:
save_crawl(website, time.time(), 0,0,0,0,0,0,)
else:
update_crawl(website, time.time(), 0,0,0,0,0,0)
except:
# could be because website is down or the timeout
print(f"[red] [-] Coundn't Crwal : {website} | Thread : {th}[/red]")
save_crawl(website, time.time(), "ERROR OCCURED", 0, 0, 0, 0, 0)
continue
try:
lang = detect(website_txt)
except:
lang = "un-dic"
if URL_SCAN:
mal = scan_url(website)
website_txt_ = remove_html(website_txt)
if Scan_Bad_Words:
lang_18 = lang_d(website_txt_)
keywords = []
desc = ""
soup = BeautifulSoup(website_txt, 'html.parser')
for meta in soup.findAll("meta"):
try:
if meta["name"] == "keywords":
keywords = meta["content"]
except:
pass
try:
if meta["name"] == "description":
desc = meta["content"]
except:
pass
del soup
top_r = None
if Scan_Top_Keywords:
top_r = get_top_reccuring(website_txt_)
update_crawl(website, time.time(), mal, lang_18, lang, keywords, desc, top_r)
del mal, lang_18, lang, keywords, desc, top_r
sub_urls = []
for x in re.findall(url_extract_pattern, website_txt):
if re.match(url_pattern, x):
if ".onion" in x:
# skips onion sites
continue
if x[-1] == "/" or x.endswith(".html") or x.split("/")[-1].isalnum():
# tries to filture out not crawlable urls
sub_urls.append(x)
# removes all duplicates
sub_urls = set(sub_urls)
sub_urls = list(sub_urls)
# check for restrictions in robots.txt and filture out the urls found
for sub_url in sub_urls:
if if_waiting(sub_url):
sub_urls.remove(sub_url)
continue
site = sub_url.replace("https://", "")
site = site.replace("http://", "")
domain = site.split("/")[0]
# print(f"[green] [+] Scans - {domain} for restrictions")
rp = urllib.robotparser.RobotFileParser()
rp.set_url("http://" + domain + "/robots.txt")
# a = get_robot(domain)
if not rp.can_fetch("*", sub_url):
sub_urls.remove(sub_url)
# restricted = robots_txt.disallowed(sub_url, proxies)
# t = sub_url.split("://")[1].split("/")
# t.remove(t[0])
# t_ = ""
# for u in t:
# t_ += "/" + u
# t = t_
# restricted = tuple(restricted)
# for resk in restricted:
# if t.startswith(resk):
# sub_urls.remove(sub_url)
# break
# check if there is a need of crawling
for e in sub_urls:
z__ = if_crawled(e)
y__ = z__[0]
t__ = z__[1]
if y__:
if int(time.time()) - int(t__) < 604800: # Re-Crawls Only After 7
sub_urls.remove(e)
continue
try:
website_req = requests.get(e, headers = {"user-agent":"open crawler v 0.0.1"}, proxies = proxies, timeout = TIMEOUT)
except:
sub_urls.remove(e)
continue
try:
if not "html" in website_req.headers["Content-Type"]:
print(f"[green] [+] Skiped : {e} Because Content type not 'html' | Thread : {th}[/green]")
sub_urls.remove(e)
continue
except:
sub_urls.remove(e)
continue
del proxies
write_to_wait_list(sub_urls)
del sub_urls
WEBSITE_SCANS.remove(website_url)
print(f"[green] [+] Crawled : {website} | Thread : {th}[/green]")
ascii_art = """
[medium_spring_green]
______ ______ __
/ \ / \ | \
| $$$$$$\ ______ ______ _______ | $$$$$$\ ______ ______ __ __ __ | $$
| $$ | $$ / \ / \ | \ | $$ \$$ / \ | \ | \ | \ | \| $$
| $$ | $$| $$$$$$\| $$$$$$\| $$$$$$$\ | $$ | $$$$$$\ \$$$$$$\| $$ | $$ | $$| $$
| $$ | $$| $$ | $$| $$ $$| $$ | $$ | $$ __ | $$ \$$/ $$| $$ | $$ | $$| $$
| $$__/ $$| $$__/ $$| $$$$$$$$| $$ | $$ | $$__/ \| $$ | $$$$$$$| $$_/ $$_/ $$| $$
\$$ $$| $$ $$ \$$ \| $$ | $$ \$$ $$| $$ \$$ $$ \$$ $$ $$| $$
\$$$$$$ | $$$$$$$ \$$$$$$$ \$$ \$$ \$$$$$$ \$$ \$$$$$$$ \$$$$$\$$$$ \$$
| $$
| $$
\$$ [bold]v 0.0.1[/bold] [/medium_spring_green]
"""
# for checking the memory usage uncomment @profile
# @profile
def main():
global DB
print(ascii_art)
# Initializes MongoDB
DB = connect_db(MONGODB_URI, MONGODB_PWD)
try:
primary_url = sys.argv[1]
except:
print("\n[blue] [?] Primary Url [You can skip this part but entering] :[/blue]", end="")
primary_url = input(" ")
print("")
print("[blue] [+] Loading And Testing Proxies... .. ... .. .. .. [/blue]")
get_proxy()
if primary_url != "":
forced_crawl(primary_url)
print("")
# Starts threading
for th in range(0, MAX_THREADS):
t_d = threading.Thread(target=crawl, args=(th+1,))
t_d.daemon = True
t_d.start()
print(f"[spring_green1] [+] Started Thread : {th + 1}[/spring_green1]")
print("\n")
# while loop waiting for exit flag
while not EXIT_FLAG:
time.sleep(0.5)
if __name__ == "__main__":
main()