-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxyreaper.py
More file actions
executable file
·1541 lines (1297 loc) · 59 KB
/
proxyreaper.py
File metadata and controls
executable file
·1541 lines (1297 loc) · 59 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 python3
# -*- coding: utf-8 -*-
"""
Proxy Reaper
This script checks a list of proxies for availability, speed, and anonymity.
It supports various protocols such as HTTP, HTTPS, SOCKS4, and SOCKS5.
Results can be saved as JSON, CSV, SQLite, or TXT, and fast proxies can be
filtered and saved in a separate file.
The script supports configuration files at /etc/proxyreaper.conf and ~/.proxyreaper.conf,
automatic proxy list downloads, and provides detailed anonymity categorization.
Author: Robert Tulke
License: MIT
"""
# Application configuration
APP_NAME = "Proxy Reaper"
VERSION = "2.1.0"
import argparse
import requests
import socks
import socket
import time
import threading
import json
import csv
import re
import sys
import signal
import os
import sqlite3
import configparser
import hashlib
import concurrent.futures
import glob
from pathlib import Path
from urllib.parse import urlparse
from concurrent.futures import ThreadPoolExecutor
from colorama import init as colorama_init, Fore, Back, Style
# Initialize Colorama for ANSI color support (also on Windows)
colorama_init(autoreset=True)
# Global print lock to avoid garbled output from multiple threads
print_lock = threading.Lock()
# Global args variable to make debug flag accessible
global_args = None
# Global cache for GeoIP lookups
geoip_cache = {}
# Global results list and counter for autosave functionality
global_results = []
results_counter = 0
AUTOSAVE_FREQUENCY = 5 # Save after every 5 proxies
# Status constants for proxy checks
STATUS_FAILED = "FAILED"
# Response time categories (in milliseconds)
SPEED_ULTRAFAST = "ultrafast" # < 100ms
SPEED_FAST = "fast" # 100-500ms
SPEED_MEDIUM = "medium" # 500-1000ms
SPEED_SLOW = "slow" # > 1000ms
SPEED_THRESHOLDS = {
SPEED_ULTRAFAST: (0, 100),
SPEED_FAST: (100, 500),
SPEED_MEDIUM: (500, 1000),
SPEED_SLOW: (1000, float('inf'))
}
# Anonymity level constants
ANONYMITY_HIGH = "High Anonymous"
ANONYMITY_ANONYMOUS = "Anonymous"
ANONYMITY_HEADER_LEAK = "Anonymous (Header leak)"
ANONYMITY_TRANSPARENT = "Transparent"
ANONYMITY_FAILED = "Failed"
# Protocol constants
PROTOCOL_HTTP = "http"
PROTOCOL_HTTPS = "https"
PROTOCOL_SOCKS4 = "socks4"
PROTOCOL_SOCKS5 = "socks5"
# Complete ISO 3166-1 alpha-2 Country Codes
COUNTRY_CODES = {
# Europe
'de': 'Germany', 'fr': 'France', 'uk': 'United Kingdom', 'gb': 'United Kingdom',
'it': 'Italy', 'es': 'Spain', 'pt': 'Portugal', 'nl': 'Netherlands',
'be': 'Belgium', 'lu': 'Luxembourg', 'ch': 'Switzerland', 'at': 'Austria',
'pl': 'Poland', 'cz': 'Czech Republic', 'sk': 'Slovakia', 'hu': 'Hungary',
'ro': 'Romania', 'bg': 'Bulgaria', 'gr': 'Greece', 'cy': 'Cyprus',
'se': 'Sweden', 'no': 'Norway', 'fi': 'Finland', 'dk': 'Denmark',
'is': 'Iceland', 'ie': 'Ireland', 'ee': 'Estonia', 'lv': 'Latvia',
'lt': 'Lithuania', 'si': 'Slovenia', 'hr': 'Croatia', 'ba': 'Bosnia and Herzegovina',
'rs': 'Serbia', 'me': 'Montenegro', 'mk': 'North Macedonia', 'al': 'Albania',
'ua': 'Ukraine', 'by': 'Belarus', 'md': 'Moldova', 'ru': 'Russia', 'mt': 'Malta',
# North America
'us': 'United States', 'ca': 'Canada', 'mx': 'Mexico',
# Mittelamerika & Karibik
'gt': 'Guatemala', 'bz': 'Belize', 'sv': 'El Salvador', 'hn': 'Honduras',
'ni': 'Nicaragua', 'cr': 'Costa Rica', 'pa': 'Panama', 'cu': 'Cuba',
'jm': 'Jamaica', 'ht': 'Haiti', 'do': 'Dominican Republic', 'pr': 'Puerto Rico',
'tt': 'Trinidad and Tobago', 'bs': 'Bahamas', 'bb': 'Barbados',
# South America
'br': 'Brazil', 'ar': 'Argentina', 'cl': 'Chile', 'co': 'Colombia',
've': 'Venezuela', 'pe': 'Peru', 'ec': 'Ecuador', 'bo': 'Bolivia',
'py': 'Paraguay', 'uy': 'Uruguay', 'gy': 'Guyana', 'sr': 'Suriname',
# Asia
'cn': 'China', 'jp': 'Japan', 'kr': 'South Korea', 'kp': 'North Korea',
'tw': 'Taiwan', 'hk': 'Hong Kong', 'mo': 'Macau', 'in': 'India',
'pk': 'Pakistan', 'bd': 'Bangladesh', 'lk': 'Sri Lanka', 'np': 'Nepal',
'bt': 'Bhutan', 'mv': 'Maldives', 'th': 'Thailand', 'vn': 'Vietnam',
'mm': 'Myanmar', 'la': 'Laos', 'kh': 'Cambodia', 'my': 'Malaysia',
'sg': 'Singapore', 'id': 'Indonesia', 'ph': 'Philippines', 'bn': 'Brunei',
'tl': 'East Timor', 'mn': 'Mongolia', 'kz': 'Kazakhstan', 'uz': 'Uzbekistan',
'tm': 'Turkmenistan', 'kg': 'Kyrgyzstan', 'tj': 'Tajikistan', 'af': 'Afghanistan',
'ir': 'Iran', 'iq': 'Iraq', 'sy': 'Syria', 'jo': 'Jordan',
'lb': 'Lebanon', 'il': 'Israel', 'ps': 'Palestine', 'sa': 'Saudi Arabia',
'ye': 'Yemen', 'om': 'Oman', 'ae': 'United Arab Emirates', 'qa': 'Qatar',
'bh': 'Bahrain', 'kw': 'Kuwait', 'tr': 'Turkey', 'am': 'Armenia',
'az': 'Azerbaijan', 'ge': 'Georgia',
# Africa
'eg': 'Egypt', 'ly': 'Libya', 'tn': 'Tunisia', 'dz': 'Algeria',
'ma': 'Morocco', 'mr': 'Mauritania', 'ml': 'Mali', 'ne': 'Niger',
'td': 'Chad', 'sd': 'Sudan', 'ss': 'South Sudan', 'et': 'Ethiopia',
'er': 'Eritrea', 'dj': 'Djibouti', 'so': 'Somalia', 'ke': 'Kenya',
'ug': 'Uganda', 'tz': 'Tanzania', 'rw': 'Rwanda', 'bi': 'Burundi',
'mz': 'Mozambique', 'mw': 'Malawi', 'zm': 'Zambia', 'zw': 'Zimbabwe',
'bw': 'Botswana', 'na': 'Namibia', 'za': 'South Africa', 'ls': 'Lesotho',
'sz': 'Eswatini', 'ao': 'Angola', 'cd': 'Democratic Republic of the Congo',
'cg': 'Republic of the Congo', 'cf': 'Central African Republic', 'cm': 'Cameroon',
'gq': 'Equatorial Guinea', 'ga': 'Gabon', 'st': 'São Tomé and Príncipe',
'gw': 'Guinea-Bissau', 'gn': 'Guinea', 'sl': 'Sierra Leone', 'lr': 'Liberia',
'ci': 'Ivory Coast', 'gh': 'Ghana', 'tg': 'Togo', 'bj': 'Benin',
'bf': 'Burkina Faso', 'ng': 'Nigeria', 'sn': 'Senegal', 'gm': 'Gambia',
'mg': 'Madagascar', 'mu': 'Mauritius', 'sc': 'Seychelles', 'km': 'Comoros',
# Oceania
'au': 'Australia', 'nz': 'New Zealand', 'pg': 'Papua New Guinea', 'fj': 'Fiji',
'sb': 'Solomon Islands', 'vu': 'Vanuatu', 'nc': 'New Caledonia', 'ws': 'Samoa',
'ki': 'Kiribati', 'to': 'Tonga', 'fm': 'Micronesia', 'mh': 'Marshall Islands',
'pw': 'Palau', 'nr': 'Nauru', 'tv': 'Tuvalu',
# Special
'unknown': 'Unknown', 'private': 'Private Network', 'localhost': 'Localhost'
}
# Reverse Mapping: Country Name → Country Code (for GeoIP → TLD)
COUNTRY_TO_CODE = {v.lower(): k for k, v in COUNTRY_CODES.items()}
# Output file constants
DEFAULT_OUTPUT_DIR = "results"
DEFAULT_OUTPUT_FORMAT = "csv"
CSV_FIELDNAMES = ["proxy", "hostname", "status", "speed_category", "response_time", "country", "city", "anonymity", "protocol", "check_time"]
# Integrated banner ASCII art without version info.
BANNER_TEXT = r"""
██▓███ ██▀███ ▒█████ ▒██ ██▒▓██ ██▓ ██▀███ ▓█████ ▄▄▄ ██▓███ ▓█████ ██▀███
▓██░ ██▒▓██ ▒ ██▒▒██▒ ██▒▒▒ █ █ ▒░ ▒██ ██▒ ▓██ ▒ ██▒▓█ ▀▒████▄ ▓██░ ██▒▓█ ▀ ▓██ ▒ ██▒
▓██░ ██▓▒▓██ ░▄█ ▒▒██░ ██▒░░ █ ░ ▒██ ██░ ▓██ ░▄█ ▒▒███ ▒██ ▀█▄ ▓██░ ██▓▒▒███ ▓██ ░▄█ ▒
▒██▄█▓▒ ▒▒██▀▀█▄ ▒██ ██░ ░ █ █ ▒ ░ ▐██▓░ ▒██▀▀█▄ ▒▓█ ▄░██▄▄▄▄██ ▒██▄█▓▒ ▒▒▓█ ▄ ▒██▀▀█▄
▒██▒ ░ ░░██▓ ▒██▒░ ████▓▒░▒██▒ ▒██▒ ░ ██▒▓░ ░██▓ ▒██▒░▒████▒▓█ ▓██▒▒██▒ ░ ░░▒████▒░██▓ ▒██▒
▒▓▒░ ░ ░░ ▒▓ ░▒▓░░ ▒░▒░▒░ ▒▒ ░ ░▓ ░ ██▒▒▒ ░ ▒▓ ░▒▓░░░ ▒░ ░▒▒ ▓▒█░▒▓▒░ ░ ░░░ ▒░ ░░ ▒▓ ░▒▓░
░▒ ░ ░▒ ░ ▒░ ░ ▒ ▒░ ░░ ░▒ ░ ▓██ ░▒░ ░▒ ░ ▒░ ░ ░ ░ ▒ ▒▒ ░░▒ ░ ░ ░ ░ ░▒ ░ ▒░
░░ ░░ ░ ░ ░ ░ ▒ ░ ░ ▒ ▒ ░░ ░░ ░ ░ ░ ▒ ░░ ░ ░░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░
"""
# Default configuration values
DEFAULT_CONFIG = {
'general': {
'timeout': '5',
'concurrent': '10',
'response_time_filter': '1000',
'test_url': 'https://www.google.com'
},
'output': {
'format': 'json',
'fast_only': 'false',
'save_directory': 'results'
},
'proxysources': {
'urls': '' # Comma-separated list of URLs
},
'advanced': {
'debug': 'false',
'anonymity_check_url': 'https://httpbin.org/get'
}
}
# Define anonymity levels with their colors
ANONYMITY_LEVELS = {
"High Anonymous": {"color": "high_anonymous", "description": "Your IP and proxy status are hidden"},
"Anonymous": {"color": "anonymous", "description": "Your IP is hidden but proxy is detected"},
"Anonymous (Header leak)": {"color": "anonymous_header_leak", "description": "Your IP is hidden but proxy headers are visible"},
"Transparent": {"color": "transparent", "description": "Your original IP is visible"},
"Failed": {"color": "error", "description": "Could not determine anonymity level"}
}
def clear_screen():
print("\033c", end="")
def debug_print(message, level="info", lock=None):
"""
Print messages with different colors based on level and respect debug flag.
Args:
message (str): The message to print
level (str): The level of the message (info, success, warning, error, debug, etc.)
lock (threading.Lock, optional): Lock to use for thread-safe printing
Returns:
None
"""
if level == "debug" and (global_args is None or not global_args.debug):
return
colors = {
"info": Fore.CYAN,
"success": Fore.GREEN,
"warning": Fore.YELLOW,
"error": Fore.RED,
"debug": Fore.MAGENTA,
"high_anonymous": Fore.GREEN + Style.BRIGHT,
"anonymous": Fore.BLUE + Style.BRIGHT,
"anonymous_header_leak": Fore.YELLOW,
"transparent": Fore.RED,
}
color = colors.get(level, Fore.WHITE)
formatted_message = f"{color}{message}{Style.RESET_ALL}"
if lock:
with lock:
print(formatted_message, flush=True)
else:
print(formatted_message, flush=True)
def display_banner():
"""
Displays the integrated banner with a red gradient.
After drawing the ASCII art, it prints the version info (highlighted in blue)
right-aligned on a separate line.
"""
lines = BANNER_TEXT.strip("\n").splitlines()
total_lines = len(lines)
# Determine the maximum width among the lines
max_width = max(len(line.rstrip()) for line in lines)
# Define a list of red shades using ANSI 256-color codes (from bright red to dark red)
red_shades = [196, 160, 124, 88]
for i, line in enumerate(lines):
shade_index = int(i / total_lines * (len(red_shades) - 1))
color_code = red_shades[shade_index]
ansi_color = f"\033[38;5;{color_code}m"
with print_lock:
print(ansi_color + line.rstrip() + "\033[0m", flush=True)
# Prepare version info right aligned to the banner width.
version_str = f"{APP_NAME} v{VERSION}"
padding = " " * (max_width - len(version_str)) if len(version_str) < max_width else ""
with print_lock:
print(padding + Fore.LIGHTBLACK_EX + Style.BRIGHT + version_str + Style.RESET_ALL, flush=True)
def load_config():
"""
Load configuration from config files with priority:
1. ~/.proxyreaper.conf
2. /etc/proxyreaper.conf
3. Default values
Returns:
configparser.ConfigParser: Loaded configuration
"""
config = configparser.ConfigParser()
# Set default values
for section, options in DEFAULT_CONFIG.items():
if not config.has_section(section):
config.add_section(section)
for key, value in options.items():
config.set(section, key, value)
# Check for system-wide config
system_config = '/etc/proxyreaper.conf'
if os.path.isfile(system_config):
debug_print(f"Loading system config from {system_config}", "debug")
config.read(system_config)
# Check for user config (overrides system config)
user_config = os.path.expanduser('~/.proxyreaper.conf')
if os.path.isfile(user_config):
debug_print(f"Loading user config from {user_config}", "debug")
config.read(user_config)
return config
def create_default_config(path):
"""
Create a default configuration file at the specified path.
Args:
path (str): Path where to create the config file
Returns:
bool: True if successful, False otherwise
"""
config = configparser.ConfigParser()
for section, options in DEFAULT_CONFIG.items():
config.add_section(section)
for key, value in options.items():
config.set(section, key, value)
try:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, 'w') as configfile:
config.write(configfile)
return True
except Exception as e:
debug_print(f"Error creating config file: {str(e)}", "error", print_lock)
return False
def override_config_with_args(config, args):
"""
Override configuration with command line arguments.
Args:
config (configparser.ConfigParser): Configuration to override
args (argparse.Namespace): Command line arguments
Returns:
configparser.ConfigParser: Updated configuration
"""
# Map of argument names to config sections and keys
arg_map = {
'timeout': ('general', 'timeout'),
'concurrent': ('general', 'concurrent'),
'response_time': ('general', 'response_time_filter'),
'url': ('general', 'test_url'),
'output': ('output', 'format'),
'fast_only': ('output', 'fast_only'),
'debug': ('advanced', 'debug')
}
for arg_name, (section, key) in arg_map.items():
arg_value = getattr(args, arg_name, None)
if arg_value is not None:
if isinstance(arg_value, bool):
arg_value = str(arg_value).lower()
else:
arg_value = str(arg_value)
config.set(section, key, arg_value)
return config
def get_public_ip():
"""
Determines the user's actual public IP address using fallback services.
Returns:
str: Public IP address or "Unknown" if not found
"""
services = [
'https://api64.ipify.org?format=json',
'https://ipinfo.io/json',
'https://api.my-ip.io/ip.json',
'https://api.ipify.org?format=json'
]
for service in services:
try:
debug_print(f"Trying to get public IP from {service}", "debug", print_lock)
response = requests.get(service, timeout=5)
if response.status_code == 200:
data = response.json()
for key in ["ip", "ip_addr", "origin"]:
ip = data.get(key)
if ip:
debug_print(f"Successfully retrieved public IP {ip} from {service}", "debug", print_lock)
return ip
except (requests.RequestException, json.JSONDecodeError) as e:
debug_print(f"Failed to get IP from {service}: {str(e)}", "debug", print_lock)
continue
debug_print("Could not determine public IP from any service", "warning", print_lock)
return "Unknown"
def parse_proxies(proxy_input, auto_mode=False):
"""
Parse proxy input which can be a single proxy, a comma-separated list,
a file path, glob patterns, or URLs in automatic mode.
Args:
proxy_input (str): Input string containing proxies, file path, or glob pattern
auto_mode (bool): Whether to download proxies from URLs
Returns:
list: List of parsed proxies
"""
proxies = []
# Handle automatic mode
if auto_mode:
debug_print("Automatic mode enabled, downloading proxy lists...", "info", print_lock)
if not proxy_input:
# Use URLs from config
config = load_config()
urls_str = config.get('proxysources', 'urls', fallback='')
urls = [url.strip() for url in urls_str.split(',') if url.strip()]
else:
# Use URLs from command line
urls = [url.strip() for url in proxy_input.split(',') if url.strip()]
for url in urls:
try:
debug_print(f"Downloading proxies from {url}", "info", print_lock)
response = requests.get(url, timeout=10)
if response.status_code == 200:
content = response.text
# Extract proxies from content (assumes one proxy per line)
url_proxies = [line.strip() for line in content.splitlines()
if line.strip() and not line.strip().startswith('#')]
debug_print(f"Downloaded {len(url_proxies)} proxies from {url}", "success", print_lock)
proxies.extend(url_proxies)
else:
debug_print(f"Failed to download from {url}: HTTP {response.status_code}", "error", print_lock)
except Exception as e:
debug_print(f"Error downloading from {url}: {str(e)}", "error", print_lock)
# Handle standard file or comma-separated list
elif ',' in proxy_input:
proxies = [p.strip() for p in proxy_input.split(',') if p.strip()]
debug_print(f"Parsed {len(proxies)} proxies from comma-separated input", "debug", print_lock)
# Check for glob patterns (*, ?, [])
elif any(char in proxy_input for char in ['*', '?', '[', ']']):
matched_files = glob.glob(proxy_input)
if not matched_files:
debug_print(f"No files matched pattern: {proxy_input}", "error", print_lock)
sys.exit(1)
debug_print(f"Found {len(matched_files)} file(s) matching pattern: {proxy_input}", "info", print_lock)
for filepath in matched_files:
try:
with open(filepath, 'r', encoding='utf-8') as f:
file_proxies = [line.strip() for line in f if line.strip() and not line.strip().startswith('#')]
proxies.extend(file_proxies)
debug_print(f"Loaded {len(file_proxies)} proxies from {filepath}", "debug", print_lock)
except Exception as e:
if global_args and global_args.debug:
debug_print(f"Error reading file {filepath}: {str(e)}", "error", print_lock)
else:
debug_print(f"Error reading file {filepath}", "error", print_lock)
if proxies:
debug_print(f"Total: Loaded {len(proxies)} proxies from {len(matched_files)} file(s)", "success", print_lock)
elif proxy_input.endswith('.txt'):
try:
with open(proxy_input, 'r', encoding='utf-8') as f:
proxies = [line.strip() for line in f if line.strip() and not line.strip().startswith('#')]
debug_print(f"Loaded {len(proxies)} proxies from file {proxy_input}", "debug", print_lock)
except FileNotFoundError:
debug_print(f"File {proxy_input} not found.", "error", print_lock)
sys.exit(1)
except Exception as e:
if global_args and global_args.debug:
debug_print(f"Error reading file {proxy_input}: {str(e)}", "error", print_lock)
else:
debug_print(f"Error reading file {proxy_input}", "error", print_lock)
sys.exit(1)
else:
proxies.append(proxy_input)
debug_print(f"Using single proxy: {proxy_input}", "debug", print_lock)
# Validate and normalize proxies
valid_proxies = validate_proxies(proxies)
if not valid_proxies:
debug_print("No valid proxies found after validation.", "error", print_lock)
return valid_proxies
def validate_proxies(proxies):
"""
Validate and normalize proxy formats.
Args:
proxies (list): List of proxy strings to validate
Returns:
list: List of validated and normalized proxies
"""
valid_proxies = []
invalid_proxies = []
for proxy in proxies:
# Strip whitespace
proxy = proxy.strip()
# Skip empty lines
if not proxy:
continue
# Check for protocol
has_protocol = '://' in proxy
if has_protocol:
# Validate protocol://host:port format
match = re.match(r'^(https?|socks[45])://(?:([^:@]+)(?::([^@]+))?@)?([^:]+):(\d+)/?$', proxy)
if match:
protocol, username, password, host, port = match.groups()
# Validate port number
try:
port_num = int(port)
if port_num < 1 or port_num > 65535:
invalid_proxies.append((proxy, "Port number out of valid range (1-65535)"))
continue
except ValueError:
invalid_proxies.append((proxy, "Invalid port number"))
continue
# Validate protocol
if protocol not in ['http', 'https', 'socks4', 'socks5']:
invalid_proxies.append((proxy, f"Unsupported protocol: {protocol}"))
continue
# Validate hostname
if not re.match(r'^[a-zA-Z0-9.-]+$', host):
invalid_proxies.append((proxy, "Invalid hostname"))
continue
# Rebuild the proxy with consistent format
auth_part = f"{username}:{password}@" if username and password else ""
valid_proxy = f"{protocol}://{auth_part}{host}:{port}"
valid_proxies.append(valid_proxy)
else:
invalid_proxies.append((proxy, "Invalid format for proxy with protocol"))
else:
# Validate host:port format
match = re.match(r'^([^:]+):(\d+)$', proxy)
if match:
host, port = match.groups()
# Validate port number
try:
port_num = int(port)
if port_num < 1 or port_num > 65535:
invalid_proxies.append((proxy, "Port number out of valid range (1-65535)"))
continue
except ValueError:
invalid_proxies.append((proxy, "Invalid port number"))
continue
# Validate hostname
if not re.match(r'^[a-zA-Z0-9.-]+$', host):
invalid_proxies.append((proxy, "Invalid hostname"))
continue
# Use http as default protocol
valid_proxies.append(f"http://{host}:{port}")
else:
invalid_proxies.append((proxy, "Invalid format, expected host:port"))
# Log invalid proxies in debug mode
if invalid_proxies:
debug_print(f"Skipping {len(invalid_proxies)} invalid proxies:", "warning", print_lock)
for proxy, reason in invalid_proxies:
debug_print(f" - {proxy}: {reason}", "debug", print_lock)
debug_print(f"Validated {len(valid_proxies)} proxies", "debug", print_lock)
return valid_proxies
def sanitize_proxy(proxy):
"""
Remove any unsafe characters from proxy string.
Args:
proxy (str): Proxy string to sanitize
Returns:
str: Sanitized proxy string
"""
return re.sub(r'[^a-zA-Z0-9.:@/_-]', '', proxy)
def get_geoip_info(ip):
"""
Get geographical information about an IP address.
Uses caching to avoid repeated requests for the same IP.
Args:
ip (str): IP address to lookup
Returns:
tuple: (country, city) information
"""
global geoip_cache
# Check cache first
if ip in geoip_cache:
debug_print(f"GeoIP cache hit for {ip}", "debug", print_lock)
return geoip_cache[ip]
debug_print(f"GeoIP lookup for {ip}", "debug", print_lock)
services = [
{'url': f'https://ipinfo.io/{ip}/json', 'country_key': 'country', 'city_key': 'city'},
{'url': f'https://freegeoip.app/json/{ip}', 'country_key': 'country_name', 'city_key': 'city'},
{'url': f'https://ipapi.co/{ip}/json/', 'country_key': 'country_name', 'city_key': 'city'}
]
for service in services:
try:
response = requests.get(service['url'], timeout=5)
if response.status_code == 200:
data = response.json()
country = data.get(service['country_key'], "Unknown")
city = data.get(service['city_key'], "Unknown")
# Cache the result
geoip_cache[ip] = (country, city)
debug_print(f"Got geo info for {ip}: {country}, {city}", "debug", print_lock)
return country, city
except (requests.RequestException, json.JSONDecodeError) as e:
debug_print(f"Failed to get geo info from {service['url']}: {str(e)}", "debug", print_lock)
continue
# Cache the "Unknown" result to avoid repeated failures
geoip_cache[ip] = ("Unknown", "Unknown")
return "Unknown", "Unknown"
def check_anonymity(proxy, anonymity_check_url, original_ip):
"""
Checks if a proxy hides the IP address and evaluates its anonymity level.
Args:
proxy (str): Proxy to check
anonymity_check_url (str): URL to use for checking anonymity
original_ip (str): Original IP address for comparison
Returns:
tuple: (detected_ip, anonymity_level)
"""
try:
debug_print(f"Checking anonymity for {proxy}", "debug", print_lock)
# Extended headers to check
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
}
response = requests.get(
anonymity_check_url,
proxies={"http": proxy, "https": proxy},
headers=headers,
timeout=10
)
if response.status_code != 200:
debug_print(f"Anonymity check failed with status code {response.status_code}", "debug", print_lock)
return "Unknown", "Failed"
try:
data = response.json()
except json.JSONDecodeError:
debug_print(f"Anonymity check failed: Invalid JSON response", "debug", print_lock)
return "Unknown", "Failed"
proxy_ip = data.get("ip", data.get("origin", "Unknown"))
headers_info = data.get("headers", {})
# Convert header keys to case-insensitive dictionary
headers_info = {k.lower(): v for k, v in headers_info.items()}
# Log all headers in debug mode
for header, value in headers_info.items():
debug_print(f"Header: {header} = {value}", "debug", print_lock)
# Check for original IP in any header (transparent proxy)
for header, value in headers_info.items():
if original_ip in str(value):
debug_print(f"Transparent proxy detected - original IP leaked in {header} header", "debug", print_lock)
return proxy_ip, "Transparent"
# Check if proxy reveals itself via common headers
proxy_headers = ["via", "proxy-connection", "forwarded", "x-forwarded"]
reveals_proxy = False
for header in headers_info:
if any(ph in header.lower() for ph in proxy_headers):
reveals_proxy = True
debug_print(f"Proxy reveals itself via {header} header", "debug", print_lock)
break
# Determine anonymity level
if proxy_ip != original_ip:
if not reveals_proxy:
# High anonymity: Different IP and no proxy headers
debug_print(f"High anonymous proxy detected: {proxy_ip}", "debug", print_lock)
return proxy_ip, "High Anonymous"
else:
# Regular anonymity: Different IP but proxy headers present
debug_print(f"Anonymous proxy with header leak detected: {proxy_ip}", "debug", print_lock)
return proxy_ip, "Anonymous (Header leak)"
else:
# Transparent: Same IP
debug_print(f"Transparent proxy detected: {proxy_ip}", "debug", print_lock)
return proxy_ip, "Transparent"
except requests.RequestException as e:
debug_print(f"Anonymity check exception: {str(e)}", "debug", print_lock)
return "Unknown", "Failed"
def create_socket_connection(proxy_type, proxy_host, proxy_port, target_host, target_port, timeout):
"""
Create a SOCKS connection to test SOCKS4/SOCKS5 proxies.
Args:
proxy_type (str): Type of proxy (socks4 or socks5)
proxy_host (str): Proxy host address
proxy_port (int): Proxy port number
target_host (str): Target host to connect to
target_port (int): Target port to connect to
timeout (int): Connection timeout in seconds
Returns:
bool: True if connection was successful, False otherwise
"""
debug_print(f"Testing {proxy_type} connection to {proxy_host}:{proxy_port}", "debug", print_lock)
s = socks.socksocket()
if proxy_type.lower() == "socks4":
s.set_proxy(socks.SOCKS4, proxy_host, int(proxy_port))
elif proxy_type.lower() == "socks5":
s.set_proxy(socks.SOCKS5, proxy_host, int(proxy_port))
else:
debug_print(f"Unsupported proxy type: {proxy_type}", "debug", print_lock)
return False
s.settimeout(timeout)
try:
s.connect((target_host, int(target_port)))
s.close()
debug_print(f"SOCKS connection successful", "debug", print_lock)
return True
except Exception as e:
debug_print(f"SOCKS connection failed: {str(e)}", "debug", print_lock)
return False
def reverse_dns_lookup(ip_address):
"""
Performs a reverse DNS lookup for an IP address.
Args:
ip_address (str): The IP address for reverse lookup
Returns:
str: Hostname if successful, otherwise the original IP address
"""
try:
hostname, _, _ = socket.gethostbyaddr(ip_address)
return hostname
except (socket.herror, socket.gaierror, socket.timeout):
# If reverse lookup fails, return the IP
return ip_address
except Exception:
return ip_address
def prepare_output_directory(config):
"""
Creates output directory and returns the path.
Args:
config (configparser.ConfigParser): Configuration object
Returns:
str: Path to output directory
"""
save_dir = config.get('output', 'save_directory', fallback=DEFAULT_OUTPUT_DIR)
os.makedirs(save_dir, exist_ok=True)
return save_dir
def generate_timestamp():
"""
Generates a timestamp string for filenames.
Returns:
str: Timestamp in format YYYYMMDD_HHMMSS
"""
return time.strftime("%Y%m%d_%H%M%S")
def build_filename(save_dir, prefix, extension, timestamp=None, suffix=None):
"""
Creates a complete file path with optional timestamp and suffix.
Args:
save_dir (str): Target directory
prefix (str): Filename prefix (e.g. "proxy_results", "fast_proxies")
extension (str): File extension without dot (e.g. "json", "csv", "txt")
timestamp (str, optional): Timestamp string. Auto-generated if None
suffix (str, optional): Additional suffix before extension (e.g. "partial", "final")
Returns:
str: Complete file path
"""
if timestamp is None:
timestamp = generate_timestamp()
if suffix:
filename = f"{prefix}_{timestamp}_{suffix}.{extension}"
else:
filename = f"{prefix}_{timestamp}.{extension}"
return os.path.join(save_dir, filename)
def autosave_results(results, config, in_progress=True):
"""
Automatically save results at regular intervals.
Args:
results (list): List of proxy check results
config (configparser.ConfigParser): Configuration
in_progress (bool): Whether this is an in-progress save or final
Returns:
None
"""
global results_counter
if not results:
return
# Create output directory and generate filename
save_dir = prepare_output_directory(config)
status = "partial" if in_progress else "final"
filename = build_filename(save_dir, "proxy_results", "json", suffix=status)
# Save as JSON
with open(filename, "w") as f:
json.dump(results, f, indent=4)
if in_progress:
debug_print(f"Autosaved {len(results)} results to {filename}", "debug", print_lock)
else:
debug_print(f"Final results saved to {filename}", "success", print_lock)
def save_as_json(results, filename):
"""
Saves results as JSON file.
Args:
results (list): List of proxy results
filename (str): Complete file path
Returns:
None
"""
with open(filename, "w") as f:
json.dump(results, f, indent=4)
debug_print(f"Results saved as JSON: {filename}", "success", print_lock)
def save_as_csv(results, filename):
"""
Saves results as CSV file.
Args:
results (list): List of proxy results
filename (str): Complete file path
Returns:
None
"""
with open(filename, "w", newline='') as f:
writer = csv.DictWriter(f, fieldnames=CSV_FIELDNAMES)
writer.writeheader()
writer.writerows(results)
debug_print(f"Results saved as CSV: {filename}", "success", print_lock)
def save_as_sqlite(results, filename):
"""
Saves results as SQLite database.
Args:
results (list): List of proxy results
filename (str): Complete file path
Returns:
None
"""
conn = sqlite3.connect(filename)
cursor = conn.cursor()
# Create table
cursor.execute('''
CREATE TABLE IF NOT EXISTS proxies (
proxy TEXT PRIMARY KEY,
status TEXT,
response_time REAL,
country TEXT,
city TEXT,
anonymity TEXT,
protocol TEXT,
check_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Insert data
for result in results:
try:
cursor.execute(
"INSERT INTO proxies (proxy, status, response_time, country, city, anonymity, protocol) VALUES (?, ?, ?, ?, ?, ?, ?)",
(
result["proxy"],
result["status"],
result["response_time"] if result["response_time"] != "N/A" else None,
result["country"],
result["city"],
result["anonymity"],
result["protocol"]
)
)
except sqlite3.IntegrityError:
# Skip duplicates
pass
conn.commit()
conn.close()
debug_print(f"Results saved as SQLite database: {filename}", "success", print_lock)
def apply_filters(results, filter_status, filter_anonymity, filter_protocol, filter_country, filter_tld):
"""
Applies all filters to the results list.
Args:
results (list): List of proxy results
filter_status (list): List of desired speed statuses
filter_anonymity (list): List of desired anonymity levels
filter_protocol (list): List of desired protocols
filter_country (list): List of desired country codes
filter_tld (list): List of desired TLDs (corresponds to country codes via GeoIP)
Returns:
list: Filtered results list
"""
filtered = results
# Filter only working proxies (not failed)
filtered = [r for r in filtered if r["status"] != STATUS_FAILED]
# Filter by status (speed category)
if filter_status:
filtered = [r for r in filtered if r["speed_category"] in filter_status]
# Filter by anonymity
if filter_anonymity:
anonymity_map = {
'highanonymous': ANONYMITY_HIGH,
'anonymous': ANONYMITY_ANONYMOUS,
'headerleak': ANONYMITY_HEADER_LEAK,
'transparent': ANONYMITY_TRANSPARENT
}
allowed_anonymity = [anonymity_map.get(a, a) for a in filter_anonymity]
filtered = [r for r in filtered if r["anonymity"] in allowed_anonymity]
# Filter by protocol
if filter_protocol:
filtered = [r for r in filtered if r["protocol"] in filter_protocol]
# Filter by country code
if filter_country:
# Convert country names to lowercase for comparison
filtered_by_country = []
for r in filtered:
country_name = r.get("country", "").lower()
# Check if country code is in COUNTRY_CODES or country name matches
country_code = COUNTRY_TO_CODE.get(country_name, "unknown")
if country_code in filter_country or country_name in filter_country:
filtered_by_country.append(r)
filtered = filtered_by_country
# Filter by TLD (same as country code for GeoIP-based filtering)
if filter_tld:
filtered_by_tld = []
for r in filtered:
country_name = r.get("country", "").lower()
country_code = COUNTRY_TO_CODE.get(country_name, "unknown")
if country_code in filter_tld:
filtered_by_tld.append(r)
filtered = filtered_by_tld
return filtered