-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcloudget.py
More file actions
executable file
·1683 lines (1584 loc) · 74 KB
/
cloudget.py
File metadata and controls
executable file
·1683 lines (1584 loc) · 74 KB
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# cloudget rebirth! v0.78
# release date: September 1, 2020
# author: vvn < vvn @ eudemonics . org >
#####
##### USER LICENSE AGREEMENT & DISCLAIMER
##### copyright, copyleft (C) 2015-2020 vvn < vvn @ eudemonics . org >
#####
##### This program is FREE software: you can use it, redistribute it and/or modify
##### it as you wish. Copying and distribution of this file, with or without modification,
##### are permitted in any medium without royalty provided the copyright
##### notice and this notice are preserved. This program is offered AS-IS,
##### WITHOUT ANY WARRANTY; without even the implied warranty of
##### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
##### GNU General Public License for more details.
#####
##### For more information, please refer to the "LICENSE AND NOTICE" file that should
##### accompany all official download releases of this program.
#####
## latest updates to program will always be found here:
## https://github.com/eudemonics/cloudget
##
## to update: from program folder in terminal or git shell, enter 'git pull'
##### enjoy!
import sys, argparse, subprocess, os, re, random, requests, string, time, traceback
#from requests.packages.urllib3.exceptions import InsecureRequestWarning
#requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from datetime import date, datetime
try:
from urlparse import urlparse
except:
pass
try:
from urllib.parse import urlparse
except:
pass
if sys.version_info.major == 3:
try:
os.system('pip3 install urllib.parse')
except:
print('\nUnable to install the urllib.parse module via pip3. This script requires this module to run. Please install the urllib.parse module for Python 3, or urlparse for Python 2, and run again.\n')
sys.exit(1)
else:
try:
os.system('pip install urlparse')
except:
print('\nUnable to install the urlparse module via pip. This script requires this module to run. Please install the urlparse module for Python 2, or urllib.parse for Python 3, and run again.\n')
sys.exit(1)
from subprocess import PIPE, check_output, Popen
try:
import cfscrape
except:
pass
try:
os.system('pip install cfscrape')
import cfscrape
except:
print('\nunable to install the cfscrape module via pip. this script requires cfscrape to run. get it here: https://github.com/Anorov/cloudflare-scrape \n')
sys.exit(1)
intro = '''\n
\033[40m\033[34m=============================================================\033[0m
\033[40m\033[32m=============================================================\033[0m
\033[40m\033[37;1m------------------ CLOUDGET REBIRTH! v0.78 ------------------\033[0m
\033[40m\033[34;21m=============================================================\033[0m
\033[40m\033[32m=============================================================\033[0m
\033[40m\033[35;1m----------------------- author : vvn ------------------------\033[0m
\033[40m\033[35m--------------- vvn [at] eudemonics [dot] org ---------------\033[0m
\033[40m\033[34;1m=============================================================\033[0m
\033[40m\033[36;1m--------------- help support my work: donate! ---------------\033[0m
\033[40m\033[33;1m-------------------- paypal.me/eudemonics -------------------\033[0m
\033[40m\033[33;1m-------------------- via cash app: $lvvn --------------------\033[0m
\033[40m\033[33;1m---------------- via venmo app: $eudemonics -----------------\033[0m
\033[40m\033[33;1m-------- via BTC: 1KQvnea8VtnXFEwynVQ8kgeqjsS4rQZFUR --------\033[0m
\033[40m\033[34;1m=============================================================\033[0m
\033[40m\033[37;1m------------------ thanks for the support! ------------------\033[0m
\033[40m\033[34;1m=============================================================\033[0m
\033[21m\n'''
if os.name == 'nt' or sys.platform == 'win32':
intro = '''\n
=============================================================
=============================================================
------------------ CLOUDGET REBIRTH! v0.78 ------------------
=============================================================
=============================================================
----------------------- author : vvn ------------------------
--------------- vvn [at] eudemonics [dot] org ---------------
=============================================================
--------------- help support my work: donate! ---------------
-------------------- paypal.me/eudemonics -------------------
-------------------- via cash app: $lvvn --------------------
---------------- via venmo app: $eudemonics -----------------
-------- via BTC: 1KQvnea8VtnXFEwynVQ8kgeqjsS4rQZFUR --------
=============================================================
------------------ thanks for the support! ------------------
=============================================================
\n'''
print(intro)
try:
from bs4 import BeautifulSoup, UnicodeDammit
except:
pass
try:
os.system('pip install BeautifulSoup')
from bs4 import BeautifulSoup
except:
print('BeautifulSoup module is required to run the script.')
sys.exit(1)
global cfurl
global usecurl
global writeout
global depth
global useproxy
global debug
global depth
global finished
global firsturl
global img
global imgdone
global single
global outpath
global links
single = 0
usecurl = 0
writeout = 0
depth = 0
useproxy = 0
debug = 0
depth = 0
links = 0
img = 0
imgdone = 0
outpath = 'download'
finished = []
parser = argparse.ArgumentParser(description="a script to automatically bypass anti-robot measures, scrape for links, and automate downloading multiple files from servers behind a cloudflare proxy")
parser.add_argument('-u', '--url', action='store', help='[**REQUIRED**] full cloudflare URL to retrieve, beginning with http(s)://', required=True)
parser.add_argument('-o', '--output', nargs='?', default='', const='output', dest='output', metavar='SAVE_PATH', help='save returned content to \'download\' sub-directory. use %(metavar)s to change this to a different save path.', required=False)
parser.add_argument('-l', '--links', help='scrape content returned from server for links', action='store_true', required=False)
parser.add_argument('-s', '--single', help='select single link(s) instead of fetching everything', action='store_true', required=False)
parser.add_argument('-c', '--curl', nargs='?', default='empty', const='curl', dest='curl', metavar='CURL_OPTS', help='use cURL. use %(metavar)s to pass optional cURL parameters. (for more info try \'curl --manual\')', required=False)
parser.add_argument('-p', '--proxy', action='store', metavar='PROXY_SERVER:PORT', help='use a proxy to connect to remote server at [protocol]://[host]:[port] (example: -p http://localhost:8080) **only use HTTP or HTTPS protocols!', required=False)
parser.add_argument('-i', '--img', help='scrape page for image files and save to \'img\' subdirectory', action='store_true', required=False)
parser.add_argument('-d', '--debug', help='show detailed stack trace on exceptions', action='store_true', required=False)
parser.add_argument('--version', action='version', version='%(prog)s v0.78 by vvn <vvn@eudemonics.org>, released September 1, 2020.')
args = parser.parse_args()
if args.output:
writeout = 1
outpath = args.output
if args.output == 'output':
outpath = 'download'
elif args.output is None:
writeout = 0
else:
writeout = 0
if args.links:
links = 1
if args.single:
single = 1
if args.img:
img = 1
if args.debug:
debug = 1
if args.proxy:
useproxy = 1
proxy = args.proxy
if not re.search(r'^(http[s]?|socks(4[a]?|5)?)', proxy):
print("\ninvalid argument supplied for proxy server. must specify as [protocol]://[server]:[port], where [protocol] is either http or https. (for example, http://127.0.0.1:8080) \n")
sys.exit(1)
x = urlparse(args.proxy)
proxyhost = str(x.netloc)
proxytype = str(x.scheme)
if args.curl in 'empty':
usecurl = 0
elif args.curl == 'curl':
usecurl = 1
else:
usecurl = 1
global curlopts
curlopts = args.curl
cfurl = args.url
firsturl = cfurl.rstrip('/')
print("\nURL TO FETCH: %s \n" % cfurl)
if 'proxy' in locals():
if 'https' in proxytype:
proxystring = {'https': '%s' % proxyhost}
else:
proxystring = {'http': '%s' % proxyhost}
print("using %s proxy server: %s \n" % (str(proxytype.upper()), str(proxyhost)))
else:
proxystring = None
print("not using proxy server \n")
if not re.match(r'^http$', cfurl[:4]):
print("incomplete URL provided: %s \r\ntrying with http:// prepended..")
cfurl = "http://" + cfurl
depth = 0
quittext = '''
*******************************************
thanks for using CLOUDGET REBIRTH!
for help, suggestions, or other inquiries,
or to report an error, contact vvn at:
vvn @ eudemonics [dot] org
STAY SAFE. WEAR A MASK, WASH YOUR HANDS,
DON'T BE A JERK.
meow!
<3
*******************************************
'''
def getCF(cfurl, links):
checkcurl = ''
checklinks = ''
if links == 1:
checklinks = 'yes'
global followdirs
else:
checklinks = 'no'
if usecurl == 1:
checkcurl = 'yes'
else:
checkcurl = 'no'
if debug == 1:
print("\n\033[32;1mlocals: \n\033[0m")
for name, val in locals().iteritems():
print("\033[35;1m%s:\033[32;21m %s \033[0m" % (str(name), str(val)))
print("\n\033[36;1mglobals: \n\033[0m")
for name, val in globals().iteritems():
print("\n\033[35;1m%s:\033[36;21m %s \033[0m" % (str(name), str(val)))
print('\033[0m\r\n')
print("\n\033[31;1musing curl:\033[31;21m\033[33m %s \033[0m\n" % checkcurl)
print("\n\033[34;1mharvesting links:\033[34;21m\033[33m %s \033[0m\n" % checklinks)
p = urlparse(cfurl)
part = p.path.split('/')[-1]
path = p.path.strip(part)
if path == cfurl:
cfurl = cfurl.rstrip('/')
p = urlparse(cfurl)
part = p.path.split('/')[-1]
path = p.path.strip(part)
urlfqdn = p.scheme + '://' + p.netloc
childdir = ''
parent = urlfqdn + childdir + path
if '/' not in path[:1]:
parent = p.geturl()
childdir = ''
else:
if len(part) < 1:
parent = p.geturl()
childdir = path
else:
if path == '/':
if re.search(r'\.([\w]{2,4})(\?|$)', part):
parent = urlfqdn
else:
parent = urlfqdn + p.path
childdir = p.path
else:
parent = urlfqdn + path
childdir = path
childdir = childdir.strip('/')
domaindir = os.path.join(outpath, p.netloc)
parentdir = os.path.join(domaindir, childdir)
if firsturl in finished and cfurl in firsturl:
print('\nABORTING: already retrieved %s!\n') % firsturl
sys.exit(1)
global outfile
outfile = cfurl.split('?')[0]
outfile = outfile.split('/')[-1]
filename = cfurl.lstrip('https:').strip('/')
filename = filename.rstrip(outfile)
dirs = filename.split('/')
if writeout == 1 or img == 1:
global existing
global checkresume
p = urlparse(cfurl)
if not os.path.exists(outpath):
os.makedirs(outpath)
if not os.path.exists(domaindir):
os.makedirs(domaindir)
a = outpath
i = 1
for dir in dirs:
while i < len(dirs):
if not re.search(r'^(.*)\.[.]+$', dir):
a = os.path.join(a, dir)
if not os.path.exists(a):
os.makedirs(a)
i += 1
else:
break
if len(outfile) < 1 or outfile in p.netloc:
outfile = 'index.html'
outdir = filename.strip()
if '/' not in cfurl[-1:]:
cfurl = cfurl + '/'
elif '.' not in outfile:
part = outfile
outfile = outfile + '.html'
outdir = filename.rstrip(part)
else:
part = outfile
outdir = filename.rstrip(part)
fulloutdir = os.path.join(outpath, outdir)
outfile = outfile.strip('/')
if not os.path.exists(fulloutdir):
os.makedirs(fulloutdir)
print("output file: %s \n" % outfile)
global savefile
savefile = os.path.join(fulloutdir, outfile)
cwd = os.getcwd()
fullsavefile = os.path.join(cwd, savefile)
print("full path to output file: %s \n" % fullsavefile)
imgdir = os.path.join('images', outdir)
if not os.path.exists(imgdir):
os.makedirs(imgdir)
else:
if len(outfile) < 1 or outfile in p.netloc:
outfile = 'index.html'
scraper = cfscrape.create_scraper()
if os.path.exists('useragents.txt'):
uafile = open('useragents.txt', 'r+')
ualist = uafile.readlines()
else:
ualist = [
# Safari #
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/601.6.17 (KHTML, like Gecko) Version/9.1.1 Safari/601.6.17',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.9 (KHTML, like Gecko) Version/8.0 Safari/600.1.9',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.25',
'Mozilla/5.0 (iPad; U; CPU OS 5_1 like Mac OS X; en-us) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A',
# Google Chrome #
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2454.101 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1 WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
'Mozilla/5.0 (X11; CrOS x86_64 6946.86.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36',
'Mozilla/5.0 (Linux; Android 4.4; 6 Build/iOS8.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.111 Mobile Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Mozilla/5.0 (Linux; Android 5.0.2; iPad Build/LRX22G) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/47.0.0.0 Safari/537.36',
'Mozilla/5.0 (Linux; Android 5.1.1; KFFOWI Build/LMY470) AppleWebKit/537.36 (KHTML, like Gecko) Silk/46.1.66 like Chrome/46.0.2490.80 Safari/537.36', # Silk Browser on Amazon Fire
# Internet Explorer/Edge #
'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0',
'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
'Mozilla/5.0 (compatible; MSIE 10.0; AOL 9.0; AOLBuild 4327.5201; Windows NT 6.1; WOW64; Trident/6.0)',
'Mozilla/5.0 (compatible; MSIE 10.0; AOL 9.7; AOLBuild 4343.19; Windows NT 6.1; WOW64; Trident/5.0; FunWebProducts)',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.1; Trident/6.0; vr; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 810)',
'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; SAMSUNG; SGH-T899M)',
# Firefox #
'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (Windows NT 6.3; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; SunOS i86pc; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; FreeBSD amd64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; FreeBSD i386; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; Linux i586; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; OpenBSD amd64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; OpenBSD alpha; rv:47.0) Gecko/20100101 Firefox/47.0',
'Mozilla/5.0 (X11; OpenBSD sparc64; rv:47.0) Gecko/20100101 Firefox/47.0',
# Other #
'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; Avant Browser)',
'Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) FxiOS/1.1 Mobile/13C71 Safari/601.1.46',
'Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C75',
'Mozilla/5.0 (X11; Linux x86_64; rv:47.0) Gecko/20121202 Firefox/47.0 Iceweasel/47.0',
'Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16',
'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14 Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0) Opera 12.14'
]
n = random.randint(0,len(ualist)) - 1
ua = ualist[n].strip()
def cfcookie(cfurl):
sess = requests.session()
p = urlparse(cfurl)
mnt = p.scheme + '://'
sess.mount(mnt, cfscrape.CloudflareAdapter())
sess.get(cfurl)
#sess.cookies
l = sess.get(cfurl)
b = sess.cookies
if b:
c = b.items()
for s, t in c:
cs = u''.join(s).encode('utf-8').strip()
ct = u''.join(t).encode('utf-8').strip()
print('\033[34;1m' + str(cs) + '\033[0m')
print('\033[32;1m' + str(ct) + '\033[0m')
cookies = "\"cf_clearance\"=\"%s\"" % sess.cookies.get('cf_clearance')
if sess.cookies.get('__cfduid'):
cookies = cookies + ";\"__cfduid\"=\"%s\"" % sess.cookies.get('__cfduid')
else:
cookies = None
return cookies
def getimg(cfurl):
imgdone = 0
r = scraper.get(cfurl, stream=True, verify=False, proxies=proxystring, allow_redirects=True)
if 'text' in r.headers.get('Content-Type'):
soup = BeautifulSoup(r.text, "html.parser")
if soup is not None:
links = soup.findAll('img')
print('\r\n--------------------------------------------------------\r\n')
bs = soup.prettify(formatter=None)
bsu = u''.join(bs).encode('utf-8').strip()
print(bsu)
print('\r\n--------------------------------------------------------\r\n')
for link in links:
#imgurl = link.split("src=")[-1]
imgurl = link['src']
imgfile = os.path.basename(imgurl)
imgfile = imgfile.strip('/')
fullimgfile = os.path.join(imgdir, imgfile)
getkb = lambda a: round(float(float(a)/1000),2)
getmb = lambda b: round(float(float(b)/1000000),2)
getsecs = lambda s: round(float(time.mktime(s.timetuple())),2)
getdif = lambda x, y: time.strftime('%H:%M:%S', time.gmtime(getsecs(x) - y))
start = getsecs(datetime.now())
time.sleep(1)
print('\ngetting %s... \n' % str(imgfile))
ext = ['.jpg', '.jpeg', '.png', '.gif', '.tif', '.bmp']
img64 = 1
for char in ext:
if char in imgfile:
img64 = 0
break
if img64 == '1':
rand = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(4)])
dt = date.strftime(datetime.now(),"%m.%d.%Y.%H.%M.%S")
imgfile = '%s_%s.png' % (str(dt), str(rand))
fullimgfile = os.path.join(imgdir, imgfile)
imgdl = open(fullimgfile, 'wb+')
imgdl.write(imgurl.decode('base64'))
imgdl.close()
else:
imgdl = open(fullimgfile, "wb+")
download_img = scraper.get(imgurl, stream=True, verify=False, proxies=proxystring, allow_redirects=True)
filesize = download_img.headers.get('Content-Length')
dld = 0
print('\nFOUND IMAGE: %s \n' % str(imgurl))
with imgdl as dlfile:
bytesize = int(filesize)
kbsize = getkb(filesize)
mbsize = getmb(filesize)
qt = 'bytes'
size = bytesize
if kbsize > 10:
qt = 'kb'
size = kbsize
if mbsize > 1 :
qt = 'mb'
size = mbsize
print('\n\033[33mfile size:\033[31m %s %s \033[0m\n' % (str(size), qt))
for chunk in download_img.iter_content(chunk_size=2048):
if chunk:
dld += len(chunk)
dlfile.write(chunk)
done = int((30 * int(dld)) / int(filesize))
dldkb = getkb(dld)
dldmb = getmb(dld)
unit = 'b '
prog = str(round(dld,2))
if dldkb > 1:
unit = 'kb '
prog = str(round(dldkb,2))
if dldmb > 1:
unit = 'mb '
prog = str(round(dldmb,2))
sys.stdout.write("\r\033[33mdownloaded: \033[36m%s %s \033[0m[%s%s]\033[35m %d kbps \033[0mtime elapsed: \033[34m%s \033[0m\r" % (prog, unit, '\033[32m#\033[0m' * done, ' ' * (30 - done), 0.001 * (dld / ((getsecs(datetime.now()) - start) + 0.1)), (getdif(datetime.now(), start))))
dlfile.flush()
os.fsync(dlfile.fileno())
else:
break
imgdl.close()
print('\nimage saved: %s \n' % imgfile)
imgdone += 1
print('\nDOWNLOAD COUNT: %d \n' % imgdone)
print('\r\n--------------------------------------------------------\r\n')
print('\n***FINISHED DOWNLOADING ALL IMAGES.***\n')
print('\nTOTAL IMAGES: %d \n' % imgdone)
else:
found = -1
def getpage(cfurl):
r = scraper.get(cfurl, stream=True, verify=False, proxies=proxystring, allow_redirects=True)
if 'text' in r.headers.get('Content-Type'):
html = BeautifulSoup(r.text, "html.parser")
print('\r\n--------------------------------------------------------\r\n')
if debug == 1:
orenc = str(html.original_encoding)
print('\n\033[40m\033[35;1mORIGINAL ENCODING: %s \033[0m\n' % orenc)
bs = html.prettify(formatter=None)
bsu = u''.join(bs).encode('utf-8').strip()
print(bsu)
print('\r\n--------------------------------------------------------\r\n')
else:
found = -1
if debug == 1:
print('\n\033[34mDEBUG LN 530: finished list length: \033[37;1m%d \033[0m\n' % len(finished))
if img == 1 and 'imgdone' not in locals():
getimg(cfurl)
# cURL request - using cURL for cloudflare URLs doesn't seem to work
if usecurl == 1:
r = scraper.get(cfurl, stream=True, verify=False, allow_redirects=True, proxies=proxystring)
print("status: ")
print(r.status_code)
print("\ngetting cookies for %s.. \n" % cfurl)
req = "GET / HTTP/1.1\r\n"
cookie_arg = cfcookie(cfurl)
if cookie_arg:
req += "Cookie: %s\r\nUser-Agent: %s\r\n" % (cookie_arg, ua)
houtput = check_output(["curl", "--cookie", cookie_arg, "-A", ua, "-s", cfurl])
curlstring = '--cookie \'' + cookie_arg + '\' -A \'' + ua + '\' -k '
if 'curlopts' in locals():
curlstring = '--cookie \'' + cookie_arg + '\' ' + curlopts + ' -A \'' + ua + '\' -k '
else:
cookie_arg = cfscrape.get_cookie_string(cfurl)
curlstring = '-A \'' + ua + '\' -k '
if 'curlopts' in locals():
curlstring = '-# ' + curlopts + ' -A \'' + ua + '\' -k '
if proxy:
curlstring += '-x %s ' % proxy
if cookie_arg:
curlstring += '--cookie \'' + cookie_arg + '\' '
req += "Cookie: %s\r\nUser-Agent: %s\r\n" % (cookie_arg, ua)
houtput = check_output(["curl", "-A", ua, "--cookie", cookie_arg, "-s", cfurl])
else:
req += "User-Agent: %s\r\n" % ua
houtput = check_output(["curl", "-A", ua, "i", "-s", cfurl])
print('\n\033[34;1msubmitting headers:\n\033[21m\033[37m%s \033[0m\n' % req)
print("\nRESPONSE: \n%s \n" % str(houtput))
msg = "\nfetching %s using cURL.. \n" % cfurl
if writeout == 1:
if os.path.exists(savefile):
resumesize = os.path.getsize(savefile)
print("\n%s already exists! \n" % outfile)
print("\nlocal file size: %s bytes \n" % str(resumesize))
if 'existing' not in globals():
existing = 0
if existing == 0:
checkresume = input('choose an option [1-3]: 1) resume download, 2) start new download, 3) skip. --> ')
while not re.match(r'^[1-3]$', checkresume):
checkresume = input('invalid input. enter 1 to resume, 2 to start new, or 3 to skip --> ')
checkexist = input('\ndo this for all downloads? Y/N --> ')
while not re.match(r'^[YyNn]$', checkexist):
checkexist = input('invalid entry. enter Y to use same action on existing files or N to always ask --> ')
if checkexist.lower() == 'y':
existing = 1
else:
existing = 0
if checkresume == '1':
curlstring = curlstring + '-C - -o \'' + savefile + '\' '
msg = "\ntrying to resume download using cURL to %s.. \n" % savefile
elif checkresume == '2':
curlstring = curlstring + '-O '
msg = "\nstarting new download to %s.. \n" % savefile
else:
msg = "\nskipping download for %s \n" % outfile
else:
curlstring = curlstring + '-O '
msg = "\ntrying to download using cURL to %s.. \n" % savefile
#command_text = 'cd download && { curl ' + curlstring + cfurl + ' ; cd -; }'
else:
msg = "\nfetching %s using cURL.. \n" % cfurl
command_text = 'curl ' + curlstring + '-s ' + cfurl
print(msg)
print("\nsubmitting cURL command string: \n%s \n" % command_text)
output = Popen(command_text, shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)
result, errors = output.communicate()
if result is not None:
if writeout == 1 and not re.search(r'(\.(htm)l?|\.php|\.txt|\.xml|\.[aj](sp)x?|\.cfm|\.do|\.md|\.json)$',outfile):
print('\nsaved file: %s \n' % outfile)
else:
ht = BeautifulSoup(r.content, "html.parser")
htpr = ht.prettify(formatter=None)
htpr = u''.join(htpr).encode('utf-8').strip()
print(htpr)
else:
if errors:
print("\nerror: %s\n" % str(errors))
finished.append(cfurl)
elif usecurl == 0 and writeout == 1:
getkb = lambda a: round(float(float(a)/1000),2)
getmb = lambda b: round(float(float(b)/1000000),2)
getsecs = lambda s: round(float(time.mktime(s.timetuple())),2)
getdif = lambda x, y: time.strftime('%H:%M:%S', time.gmtime(getsecs(x) - y))
print("\ngetting %s... \n" % cfurl)
if os.path.exists(savefile): # FOUND SAVED FILE
# GET SIZE OF EXISTING LOCAL FILE
resumesize = os.path.getsize(savefile)
ksize = getkb(resumesize)
msize = getmb(resumesize)
sizeqt = 'kb'
fsize = ksize
if msize > 1:
sizeqt = 'mb'
fsize = msize
existsize = str(fsize) + ' ' + sizeqt
print("\n%s already exists! \n" % outfile)
print("\nlocal file size: %s \n" % existsize)
if 'existing' not in globals():
existing = 0
if existing == 0:
checkresume = input('choose an option [1-3]: 1) resume download, 2) start new download, 3) skip. --> ')
while not re.match(r'^[1-3]$', checkresume):
checkresume = input('invalid input. enter 1 to resume, 2 to start new, or 3 to skip --> ')
checkexist = input('\ndo this for all downloads? Y/N --> ')
while not re.match(r'^[YyNn]$', checkexist):
checkexist = input('invalid entry. enter Y to use same action on existing files or N to always ask --> ')
if checkexist.lower() == 'y':
existing = 1
else:
existing = 0
if checkresume == '1': # RESUME DOWNLOAD AT LAST LOCAL BYTE
dld = int(resumesize)
resumeheader = {'Range': 'bytes=%s-' % str(dld)}
dlmsg = "\nattempting to resume download for %s. this may take awhile depending on file size... \n" % outfile
df = open(savefile, 'a+b')
elif checkresume == '2': # DISREGARD SAVED FILE, START DOWNLOAD FROM TOP
dld = 0
resumeheader = None
dlmsg = "\nwriting content to \'download\' directory as file %s. this may take awhile depending on file size... \n" % outfile
df = open(savefile, 'wb+')
else: # SKIPPING DOWNLOAD
resumeheader = None
df = open(savefile, 'r+')
dlmsg = "\nskipping download for %s\n" % outfile
else: # NEW DOWNLOAD REQUEST
checkresume = '2'
dld = 0
df = open(savefile, 'wb+')
resumeheader = None
dlmsg = "\nwriting content to \'%s\' directory as file %s. this may take awhile depending on file size... \n" % (outpath, outfile)
print(dlmsg)
if not checkresume == '3': # IF NOT SKIPPING
r = scraper.get(cfurl, stream=True, headers=resumeheader, verify=False, allow_redirects=True, proxies=proxystring)
filesize = r.headers.get('Content-Length')
if checkresume == '1' and filesize is not None:
filesize = int(filesize) + int(resumesize)
filetype = r.headers.get('Content-Type')
#starttime = date.strftime(datetime.now(), "%H:%M:%S")
start = getsecs(datetime.now())
time.sleep(1)
#today = datetime.now()
#startdate = date.strftime(today,"%m-%d-%Y %H:%M:%S ")
#print("start time: %s \n" % startdate)
with df as dlfile:
if filesize is not None and 'text' not in filetype:
filesize = int(filesize)
bytesize = int(filesize)
kbsize = getkb(filesize)
mbsize = getmb(filesize)
qt = 'bytes'
size = bytesize
if kbsize > 10:
qt = 'kb'
size = kbsize
if mbsize > 1 :
qt = 'mb'
size = mbsize
print('\n\033[33mfile size:\033[31m %s %s \033[0m\n' % (str(size), qt))
for chunk in r.iter_content(chunk_size=2048):
if chunk:
dld += len(chunk)
dlfile.write(chunk)
done = int((30 * int(dld)) / int(filesize))
dldkb = getkb(dld)
dldmb = getmb(dld)
unit = 'b '
prog = str(round(dld,2))
if dldkb > 1:
unit = 'kb '
prog = str(round(dldkb,2))
if dldmb > 1:
unit = 'mb '
prog = str(round(dldmb,2))
sys.stdout.write("\r\033[33mdownloaded: \033[36m%s %s \033[0m[%s%s]\033[35m %d kbps \033[0mtime elapsed: \033[34m%s \033[0m\r" % (prog, unit, '\033[32m#\033[0m' * done, ' ' * (30 - done), 0.001 * (dld / ((getsecs(datetime.now()) - start) + 0.1)), (getdif(datetime.now(), start))))
dlfile.flush()
os.fsync(dlfile.fileno())
else:
break
elif filesize and 'text' in filetype:
dlfile.write(r.content)
dlfile.flush()
os.fsync(dlfile.fileno())
else:
for chunk in r.iter_content(chunk_size=2048):
if chunk:
dld += len(chunk)
dlfile.write(chunk)
dldkb = getkb(dld)
dldmb = getmb(dld)
unit = 'b '
prog = str(round(dld,2))
if dldkb > 1:
unit = 'kb '
prog = str(round(dldkb,2))
if dldmb > 1:
unit = 'mb '
prog = str(round(dldmb,2))
sys.stdout.write("\r\033[33mdownloaded: \033[36m%s %s \033[35m %d kbps \033[0mtime elapsed: \033[34m%s \033[0m\r" % (prog, unit, 0.001 * (dld / ((getsecs(datetime.now()) - start) + 0.1)), (getdif(datetime.now(), start))))
dlfile.flush()
os.fsync(dlfile.fileno())
else:
break
print("\r\nfile %s saved! \n" % outfile)
endclock = getsecs(datetime.now())
fin = endclock - start
totalsecs = fin
if debug == 1:
print("\n\033[34;1mSTART: \033[35;1m %s \033[0;21m\n" % str(start))
print("\n\033[34;1mEND: \033[35;1m %s \033[0;21m\n" % str(endclock))
elapsed = "%s seconds " % str(totalsecs)
if totalsecs > 60:
totalmins = float(totalsecs / 60)
mins = int(totalmins)
if mins == 1:
unitmin = "minute"
else:
unitmin = "minutes"
strmin = str(mins) + " " + str(unitmin)
secs = round(totalsecs % 60,4)
elapsed = str(strmin) + " " + str(secs) + " seconds"
if totalmins > 60:
totalhours = float(totalmins / 60 )
hours = int(totalmins / 60)
if hours == 1:
unithr = "hour"
else:
unithr = "hours"
strhr = str(hours) + " " + str(unithr)
mins = totalmins % 60
elapsed = "%s, %s mins, %s secs" % (strhr, mins, secs)
else:
hours = 0
else:
hours = 0
mins = 0
secs = totalsecs
elapsed = "%s seconds" % str(secs)
#ended = datetime.now()
#print("end time: %s \n" % enddate)
#enddate = date.strftime(ended,"%m-%d-%Y %H:%M:%S ")
print("\ndownload time elapsed: %s \n" % str(elapsed))
time.sleep(2)
print('\r\n--------------------------------------------------------\r\n')
else:
print("\nskipped download from %s.\r\nfile has not been modified.\n" % cfurl)
getpage(cfurl)
cfurl = str(cfurl.strip())
finished.append(cfurl)
else:
getpage(cfurl)
cfurl = str(cfurl.strip())
finished.append(cfurl)
def getparent(cfurl):
cff = re.match(r'^http:\/\/(.*)(\/\/)(.*)', cfurl)
if cff:
cf = 'http://' + str(cff.group(1)) + '/' + str(cff.group(3))
else:
cf = str(cfurl)
p = urlparse(cf)
part = p.path.split('/')[-1]
path = p.path.strip(part)
if path == cf:
cf = cf.rstrip('/')
p = urlparse(cf)
part = p.path.split('/')[-1]
path = p.path.strip(part)
urlfqdn = p.scheme + '://' + p.netloc
childdir = ''
parent = urlfqdn + childdir + path
if '/' not in path[:1]:
parent = p.geturl()
childdir = ''
else:
if len(part) < 1:
parent = p.geturl()
childdir = path
else:
if path == '/':
if re.search(r'\.([\w]{2,4})(\?|$)', part):
parent = urlfqdn
else:
parent = urlfqdn + p.path
childdir = p.path
else:
parevnt = urlfqdn + path
childdir = path
if '/' not in parent[-1:]:
parent = parent + '/'
return parent
def getlinks(cfurl):
r = scraper.get(cfurl, stream=True, verify=False, proxies=proxystring, allow_redirects=True)
filetype = r.headers.get('Content-Type')
filetype = str(filetype)
html = BeautifulSoup(r.text, "html.parser")
if debug == 1:
print('\n\033[40m\033[35;1mDEBUG: \nContent-Type: %s \033[0m\n' % filetype)
if 'text' in filetype:
bs = html.prettify(formatter=None)
linkresult = html.findAll('a')
if len(linkresult) > 0:
lr = []
for link in linkresult:
linkurl = link.get('href')
linkurl = str(linkurl)
matchstr = r'^(\/)?%s(\/)?$' % part
if not re.search(r'^(#)|((\.\.)?\/)$', linkurl) and not re.match(matchstr, linkurl) and 'javascript' not in linkurl:
lr.append(linkurl)
dl = 0
if single == 1:
dl = 1
lenlinks = len(lr)
while dl == 1 and lenlinks > 0:
x = 0
while x < lenlinks:
for l in lr:
y = x + 1
print('%d - %s' % (y, l))
x += 1
print('0 - CONTINUE TO DIRECTORY SELECTION OR DOWNLOAD ALL LINKS')
print('\n')
linksel = '[1-%d]' % lenlinks
lim = lenlinks + 1
selectlink = input('make a selection %s to download the corresponding link. to continue to another directory or download all links, enter 0 --> ' % linksel)
while not re.match(r'^[0-9]{1,3}$', selectlink):
selectlink = input('invalid input. please enter an integer 0-%d --> ' % lenlinks)
selectlink = int(selectlink)
while selectlink not in range(0, lim):
selectlink = input('invalid selection. please enter value between 0 and %s --> ' % lenlinks)
if selectlink == 0:
dl = 0
foundlinks = len(linkresult)
print('\ncontinuing.. \n')
break
elif selectlink in range(1, lim):
followlink = input('harvest links at the selected URL? enter Y/N --> ')
while not re.match(r'^[yYnN]$', followlink):
followlink = input('invalid entry. enter Y or N --> ')
if followlink.lower() == 'y':
following = 1
else:
following = 0
foundlinks = len(linkresult)
n = int(selectlink) - 1
lnk = lr[n]
par = getparent(cfurl)
if 'http' not in lnk[:4]:
lnk = lnk.lstrip('/')
lnk = par + lnk
getCF(lnk, following)
another = input('to choose another link to download, enter 1. to continue, enter 2. to quit, enter 3. --> ')
while not re.match(r'^[1-3]$', another):
another = input('invalid selection. please enter a value 1-3 --> ')
if another == '2':
dl = 0
break
elif another == '3':
dl = 0
print(quittext)
time.sleep(3)
print('\nexiting program.. \n')
sys.exit(0)
else:
continue
else:
dl = 0
break
foundlinks = len(linkresult)
print('\nFOUND \033[31m%s \033[0mLINKS AT \033[036m%s\033[0m:\n(hiding shortcuts and parent directories)\n' % (str(foundlinks), cfurl))
for link in linkresult:
b = link.get('href')
b = str(b)
if b not in cfurl and not re.match(r'^(\.\.)?\/$', b) and '#' not in b and 'javascript' not in str(b):
print(b)
print('\n')
else:
print('\nNO LINKS FOUND.\n')
foundlinks = 0
else:
if not re.search(r'^(.*)\.(jpg|mp3|avi|ogg|mp4|mov|gif|png|bmp|tif|wav|flac)$', cfurl):
print('\nLINKS NOT AVAILABLE FOR %s \n' % cfurl)
foundlinks = 0
time.sleep(3)
return foundlinks
def selectdir(geturl):
r = scraper.get(geturl, stream=True, verify=False, proxies=proxystring, allow_redirects=True)
html = BeautifulSoup(r.text, "html.parser")
filetype = r.headers.get('Content-Type')
filetype = str(filetype)
if debug == 1:
orenc = str(html.original_encoding)
print('\n\033[40m\033[35;1mORIGINAL ENCODING: %s \033[0m\n' % orenc)
findlinks = html.findAll('a')
dirlist = []
for link in findlinks:
b = link.get('href')
if not re.match(r'^((\.\.)?\/)$', str(b)) and '#' not in str(b) and 'javascript' not in str(b) and str(b) not in geturl:
if re.search(r'^(.*)(\/)$', str(b)):
dirlist.append(b)
p = urlparse(geturl)
part = p.path.split('/')[-1]
path = p.path.strip(part)
if path == geturl:
geturl = geturl.rstrip('/')
p = urlparse(geturl)
part = p.path.split('/')[-1]
path = p.path.strip(part)
urlfqdn = p.scheme + '://' + p.netloc
loc = geturl.lstrip('https:').strip('/')
childdir = ''
dirs = filename.split('/')
parent = urlfqdn + childdir + path
if '.' not in part and '\?' not in part and len(part) > 0 and '/' in p.path and 'text' in filetype:
childdir = p.path
if '/' not in part[1:]:
childdir = childdir + '/'
parent = urlfqdn + childdir
if '/' not in path[:1]: