Repository navigation
Expand file tree
/
Copy pathdorkwright.py
More file actions
691 lines (575 loc) · 25.2 KB
/
Copy pathdorkwright.py
File metadata and controls
691 lines (575 loc) · 25.2 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
#!/usr/bin/env python3
import argparse
import asyncio
import os
import re
from pathlib import Path
from urllib.parse import urlparse, unquote
from playwright.async_api import async_playwright
import requests
from tqdm import tqdm
async def extract_file_links(query: str, max_pages: int = 10, delay: int = 3):
file_links = set()
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
context = await browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
viewport={"width": 1600, "height": 900},
locale="en-US",
)
page = await context.new_page()
for page_num in range(max_pages):
try:
# Construct Google search URL
start = page_num * 10
search_url = f"https://www.google.com/search?q={query}&start={start}"
print(f"Searching page {page_num + 1}...", flush=True)
await page.goto(search_url, wait_until="networkidle", timeout=30000)
# Handle cookie consent if present
try:
# Look for common Google consent buttons
consent_buttons = [
'button:has-text("Accept all")',
'button:has-text("Reject all")',
'button:has-text("I agree")',
"#L2AGLb", # Google's "Accept all" button ID
'button[id="W0wltc"]', # Another common consent button
]
for selector in consent_buttons:
try:
button = page.locator(selector).first
if await button.is_visible(timeout=2000):
print(f" Handling cookie consent...", flush=True)
await button.click()
await page.wait_for_timeout(1000)
break
except:
continue
except Exception as e:
pass # No consent dialog, continue
# Wait a bit for dynamic content
await page.wait_for_timeout(2000)
# Check for CAPTCHA
page_content = await page.content()
if (
"recaptcha" in page_content.lower()
or "captcha" in page_content.lower()
):
print("\n" + "=" * 60)
print("CAPTCHA DETECTED!")
print("Please solve the CAPTCHA in the browser window.")
print("Press ENTER here when done...")
print("=" * 60 + "\n")
input() # Wait for user to press Enter
await page.wait_for_timeout(2000)
# Extract all links from search results
links = await page.evaluate(
"""
() => {
const anchors = document.querySelectorAll('a');
return Array.from(anchors).map(a => a.href);
}
"""
)
# Filter for direct file links
for link in links:
if is_file_link(link):
clean_link = clean_google_url(link)
if clean_link:
file_links.add(clean_link)
print(f" Found: {clean_link}")
# Check if there's a "Next" button
has_next = await page.evaluate(
"""
() => {
const nextButton = document.querySelector('a#pnnext');
return nextButton !== null;
}
"""
)
if not has_next:
if page_num + 1 < max_pages:
print(
f"No more pages available. Scraped {page_num + 1} of {max_pages} requested pages."
)
else:
print("Reached last page of results.")
break
# Delay before next page to avoid triggering anti-bot measures
if page_num < max_pages - 1:
print(f" Waiting {delay} seconds before next page...", flush=True)
await page.wait_for_timeout(delay * 1000)
except Exception as e:
print(f"Error on page {page_num + 1}: {e}")
continue
await browser.close()
return sorted(list(file_links))
def clean_google_url(url: str) -> str:
# Google often wraps URLs like: /url?q=https://example.com/file.pdf&sa=...
if "/url?q=" in url or "/url?url=" in url:
match = re.search(r"[?&](?:q|url)=([^&]+)", url)
if match:
return unquote(match.group(1))
# If it's already a direct URL
if url.startswith("http"):
return url
return None
def format_size(bytes_size: float) -> str:
"""Convert bytes to human-readable format"""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if bytes_size < 1024.0:
return f"{bytes_size:.2f} {unit}"
bytes_size /= 1024.0
return f"{bytes_size:.2f} PB"
def sanitize_filename(filename: str) -> str:
"""
Sanitize filename for Windows/Unix compatibility.
Removes or replaces invalid characters.
"""
# Windows forbidden characters: < > : " / \ | ? *
invalid_chars = '<>:"|?*'
for char in invalid_chars:
filename = filename.replace(char, "_")
# Replace forward/back slashes with underscores
filename = filename.replace("/", "_").replace("\\", "_")
# Remove control characters (ASCII 0-31)
filename = "".join(char for char in filename if ord(char) >= 32)
# Trim whitespace and dots from start/end
filename = filename.strip(". ")
# Ensure filename is not empty
if not filename:
filename = "file"
# Windows reserved names
reserved_names = [
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
]
name_without_ext = os.path.splitext(filename)[0].upper()
if name_without_ext in reserved_names:
filename = "_" + filename
return filename
def is_file_link(url: str) -> bool:
"""Determine if a URL points to a file based on its extension."""
url_lower = url.lower()
parsed = urlparse(url_lower)
path = parsed.path
# Skip empty paths or paths that end with /
if not path or path.endswith("/"):
return False
# Check if path has a file extension pattern: .xxx at the end or before ? or #
# Match extensions like .pdf, .docx, .tar.gz, etc.
# Pattern matches: filename ending with .extension (2-5 chars after the last dot)
pattern = r"\.[a-z0-9]{2,5}$"
# Check if path ends with an extension
if re.search(pattern, path):
return True
# Also check the full URL in case extension is before query params or fragments
# e.g., /file.pdf?download=true
if re.search(r"\.[a-z0-9]{2,5}[?#]", url_lower):
return True
return False
def save_links(links: list, output_file: str):
with open(output_file, "w", encoding="utf-8") as f:
for link in links:
f.write(f"{link}\n")
print(f"\nSaved {len(links)} links to {output_file}")
def download_with_flaresolverr(url: str, flaresolverr_url: str, timeout: int = 60):
"""Download a file using FlareSolverr to bypass Cloudflare challenges."""
try:
# Step 1: Use FlareSolverr to solve Cloudflare challenge
payload = {
"cmd": "request.get",
"url": url,
"maxTimeout": timeout * 1000, # Convert to milliseconds
}
headers = {"Content-Type": "application/json"}
flaresolverr_response = requests.post(
f"{flaresolverr_url}/v1",
headers=headers,
json=payload,
timeout=timeout + 10
)
flaresolverr_response.raise_for_status()
result = flaresolverr_response.json()
if result.get("status") == "ok":
solution = result.get("solution", {})
# Extract cookies and user agent from FlareSolverr response
cookies_list = solution.get("cookies", [])
user_agent = solution.get("userAgent", "")
# Convert cookies list to dict for requests
cookies = {cookie["name"]: cookie["value"] for cookie in cookies_list}
# Step 2: Make actual download request with solved cookies
download_headers = {
"User-Agent": user_agent
}
actual_response = requests.get(
url,
headers=download_headers,
cookies=cookies,
stream=True,
timeout=timeout
)
actual_response.raise_for_status()
return actual_response
else:
print(f"FlareSolverr error: {result.get('message', 'Unknown error')}")
return None
except Exception as e:
print(f"FlareSolverr request failed: {e}")
return None
def download_files(input_file: str, output_dir: str, proxy: str | None = None, flaresolverr_url: str | None = None):
# Create output directory
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Read URLs from file
try:
with open(input_file, "r", encoding="utf-8") as f:
urls = [line.strip() for line in f if line.strip()]
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
return
if not urls:
print(f"No URLs found in {input_file}")
return
print(f"Found {len(urls)} URLs to download")
print(f"Saving to directory: {output_dir}")
# Setup proxy configuration
proxies = None
if proxy:
proxies = {
'http': proxy,
'https': proxy
}
print(f"Using proxy: {proxy}")
if flaresolverr_url:
print(f"Using FlareSolverr: {flaresolverr_url}")
success_count = 0
failed_count = 0
total_bytes = 0
file_types = {}
import time
start_time = time.time()
# Progress bar for overall download progress
print() # Space for individual file progress bar above
pbar_overall = tqdm(
total=len(urls),
desc="Overall Progress",
unit=" file",
position=1,
bar_format="{l_bar}{bar:40}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
colour="green",
ncols=100,
leave=False, # Don't leave the progress bar after completion
)
try:
for idx, url in enumerate(urls, 1):
filename = None
try:
# Download file with progress bar
# Use FlareSolverr if configured, otherwise use regular requests (with proxy if configured)
if flaresolverr_url:
response = download_with_flaresolverr(url, flaresolverr_url)
if response is None:
raise requests.RequestException("FlareSolverr download failed")
else:
response = requests.get(url, timeout=30, stream=True, proxies=proxies)
response.raise_for_status()
# Determine filename from Content-Disposition header if available
content_disposition = response.headers.get("Content-Disposition", "")
if content_disposition:
# Try to extract filename from Content-Disposition header
# RFC 5987 encoded filename (filename*=UTF-8''...) << Seems OK
filename_match = re.search(
r"filename\*=UTF-8''([^;]+)", content_disposition
)
if filename_match:
filename = unquote(filename_match.group(1), encoding="utf-8")
else:
# Try regular filename parameter
filename_match = re.search(
r'filename=["\'"]?([^"\'";]+)', content_disposition
)
if filename_match:
# Try to decode if it looks like it's UTF-8 encoded
raw_filename = filename_match.group(1).strip("\"'")
try:
# If the filename is Latin-1 encoded but contains UTF-8 bytes
filename = raw_filename.encode("latin-1").decode(
"utf-8"
)
except (UnicodeDecodeError, UnicodeEncodeError):
filename = raw_filename
# If no filename from headers, extract from URL path
if not filename:
parsed = urlparse(url)
# URL-decode the path properly
filename = unquote(os.path.basename(parsed.path), encoding="utf-8")
# Determine correct file extension from Content-Type header
content_type = (
response.headers.get("Content-Type", "")
.split(";")[0]
.strip()
.lower()
)
# Map common MIME types to extensions
mime_to_ext = {
"application/pdf": ".pdf",
"application/msword": ".doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"application/vnd.ms-excel": ".xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
"application/vnd.ms-powerpoint": ".ppt",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
"application/zip": ".zip",
"application/x-zip-compressed": ".zip",
"text/plain": ".txt",
"text/csv": ".csv",
"image/jpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
}
# Get extension from content-type if available
correct_ext = mime_to_ext.get(content_type, "")
# If we have a filename but it has wrong extension (e.g., .aspx for a PDF)
if filename and correct_ext:
current_ext = os.path.splitext(filename)[1].lower()
# Replace extension if current one doesn't match content type
if current_ext != correct_ext and current_ext in [
".aspx",
".php",
".jsp",
".cgi",
".asp",
]:
base = os.path.splitext(filename)[0]
filename = f"{base}{correct_ext}"
# If still no filename, generate one
if not filename or "." not in filename:
ext = correct_ext if correct_ext else ""
filename = f"file_{idx}{ext}"
# Sanitize filename for filesystem compatibility
filename = sanitize_filename(filename)
output_path = os.path.join(output_dir, filename)
# Handle duplicate filenames
if os.path.exists(output_path):
base, ext = os.path.splitext(filename)
counter = 1
while os.path.exists(output_path):
filename = f"{base}_{counter}{ext}"
output_path = os.path.join(output_dir, filename)
counter += 1
# Get file size from headers if available
total_size = int(response.headers.get("content-length", 0))
# Progress bar for individual file download
desc = f"Downloading {filename[:35]}"
with tqdm(
total=total_size,
desc=desc,
unit="B",
unit_scale=True,
unit_divisor=1024,
position=0,
leave=False,
bar_format="{desc}: {percentage:3.0f}%|{bar:30}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
colour="cyan",
ncols=100,
) as pbar_file:
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
pbar_file.update(len(chunk))
file_size = os.path.getsize(output_path)
total_bytes += file_size
# Track file type
ext = os.path.splitext(filename)[1].lower()
if ext:
file_types[ext] = file_types.get(ext, 0) + 1
# Format output with padding for alignment
pbar_overall.write(
f" ✓ {filename:<50s} {format_size(file_size):>10s}"
)
success_count += 1
except requests.RequestException as e:
display_name = filename if filename else url[:50]
pbar_overall.write(f" ✗ {display_name:<50s} FAILED")
failed_count += 1
except Exception as e:
display_name = filename if filename else url[:50]
pbar_overall.write(f" ✗ {display_name:<50s} ERROR")
failed_count += 1
finally:
pbar_overall.update(1)
finally:
# Close the progress bar - it will auto-clear because leave=False
pbar_overall.close()
# Add a newline for spacing
print()
# Calculate statistics
end_time = time.time()
elapsed_time = end_time - start_time
avg_speed = total_bytes / elapsed_time if elapsed_time > 0 else 0
# Display statistics
print(f"{'='*80}")
print(f"{'DOWNLOAD STATISTICS':^80}")
print(f"{'='*80}")
print(f" Total files processed: {len(urls)}")
print(f" Successfully downloaded: {success_count}")
print(f" Failed downloads: {failed_count}")
print(f" Total size: {format_size(total_bytes)}")
print(f" Time elapsed: {elapsed_time:.2f}s")
print(f" Average speed: {format_size(avg_speed)}/s")
if file_types:
print(f"\n File types downloaded:")
for ext, count in sorted(file_types.items(), key=lambda x: x[1], reverse=True):
print(f" {ext:10s} : {count:3d} file{'s' if count != 1 else ''}")
print(f"{'='*80}")
async def main():
parser = argparse.ArgumentParser(
description="""
╔═══════════════════════════════════════════════════════════════════════════════╗
║ DORKWRIGHT - Google Dorker ║
║ Extract file links from Google search results and download them ║
╚═══════════════════════════════════════════════════════════════════════════════╝
""",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
═══════════════════════════════════════════════════════════════════════════════════
USAGE EXAMPLES:
Search and save links:
─────────────────────────────────────────────────────────────────────────────
%(prog)s -q "site:example.com filetype:doc OR filetype:docx OR filetype:dot"
%(prog)s -q "site:example.com filetype:pdf" -p 5 -o results.txt
Search and download immediately:
─────────────────────────────────────────────────────────────────────────────
%(prog)s -q "site:example.com filetype:doc" --download --download-dir downloads
Download from existing file:
─────────────────────────────────────────────────────────────────────────────
%(prog)s --input-file file_links.txt --download-dir my_files
Download with proxy or FlareSolverr (for Cloudflare bypass):
─────────────────────────────────────────────────────────────────────────────
%(prog)s --input-file file_links.txt --proxy http://127.0.0.1:8080
%(prog)s --input-file file_links.txt --flaresolverr http://localhost:8191
%(prog)s -q "site:example.com filetype:pdf" --download --flaresolverr http://localhost:8191
═══════════════════════════════════════════════════════════════════════════════════
""",
)
# Search options
parser.add_argument(
"-q",
"--query",
metavar="QUERY",
help='Google search query (e.g., "site:example.com filetype:doc")\n\n',
)
parser.add_argument(
"-p",
"--pages",
metavar="N",
type=int,
default=10,
help="Maximum number of result pages to scrape (default: 10)\n\n",
)
parser.add_argument(
"-d",
"--delay",
metavar="SECONDS",
type=int,
default=3,
help="Delay in seconds between page requests to avoid CAPTCHA (default: 3)\n\n",
)
# Output options
parser.add_argument(
"-o",
"--output",
metavar="FILE",
default="file_links.txt",
help="Output file for extracted links (default: file_links.txt)\n\n",
)
# Download options
parser.add_argument(
"--download",
action="store_true",
help="Download files after extracting links\n\n",
)
parser.add_argument(
"--download-dir",
metavar="DIR",
default="downloads",
help="Directory to save downloaded files (default: downloads)\n\n",
)
parser.add_argument(
"--input-file",
metavar="FILE",
help="Input file with URLs to download (skip search if provided)\n\n",
)
# Proxy options
parser.add_argument(
"--proxy",
metavar="URL",
help="Proxy server URL (e.g., http://127.0.0.1:8080, socks5://127.0.0.1:1080)\n\n",
)
parser.add_argument(
"--flaresolverr",
metavar="URL",
help="FlareSolverr endpoint for bypassing Cloudflare (e.g., http://localhost:8191)\n\n",
)
args = parser.parse_args()
# Mode 1: Download from existing file
if args.input_file:
download_files(args.input_file, args.download_dir, args.proxy, args.flaresolverr)
return
# Mode 2: Search and optionally download
if not args.query:
parser.error(
"the following arguments are required: -q/--query (unless using --input-file)"
)
print(f"Searching Google for: {args.query}")
print(f"Max pages: {args.pages}")
print(f"Delay between pages: {args.delay}s\n")
# Extract links
links = await extract_file_links(
query=args.query, max_pages=args.pages, delay=args.delay
)
# Display results
print(f"\n{'='*60}")
print(f"Found {len(links)} unique file links:")
print(f"{'='*60}")
for link in links:
print(link)
# Save to file
if links:
save_links(links, args.output)
# Download if requested
if args.download:
print(f"\nStarting downloads...\n")
download_files(args.output, args.download_dir, args.proxy, args.flaresolverr)
else:
print(f"\nYou can download all files with:")
print(
f" python {parser.prog} --input-file {args.output} --download-dir {args.download_dir}"
)
print(f"Or with wget:")
print(f" wget -i {args.output}")
else:
print("\nNo file links found.")
if __name__ == "__main__":
asyncio.run(main())