-
Notifications
You must be signed in to change notification settings - Fork 20
/
ddec.py
3110 lines (2799 loc) · 104 KB
/
ddec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
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 -*-
# Program: DNS Domain Expiration Checker from ak545
#
# Author of the original script: Matty < matty91 at gmail dot com >
# https://github.com/Matty9191
#
# Author of this fork: Andrey Klimov < ak545 at mail dot ru >
# https://github.com/ak545
#
# Thanks to:
# Carl Mercier (https://github.com/cmer)
# Leif (https://github.com/akhepcat)
# woodholly (https://github.com/woodholly)
# drzraf (https://github.com/drzraf)
#
# Current Version: 0.2.26.1
# Creation Date: 2019-07-05
# Date of last changes: 2024-04-15
#
# License:
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but 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.
from __future__ import unicode_literals
import pprint
from typing import List, Dict, Tuple, Optional, Any
import os
import sys
import platform
import socket
import argparse
import time
import json
from datetime import datetime
import difflib
import io
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from pathlib import Path
import subprocess
try:
import requests
except ImportError:
sys.exit(
"""You need requests!
install it from http://pypi.python.org/pypi/requests
or run 'pip install requests'"""
)
try:
import socks
except ImportError:
sys.exit(
"""You need Socks!
install it from http://pypi.python.org/pypi/PySocks
or run 'pip install PySocks'
or run 'pip install requests[socks]'"""
)
try:
import dateutil.parser
except ImportError:
sys.exit(
"""You need python-dateutil!
install it from http://pypi.python.org/pypi/python-dateutil
or run 'pip install python-dateutil'"""
)
try:
import whois
except ImportError:
sys.exit(
"""You need python-whois!
install it from http://pypi.python.org/pypi/python-whois
or run 'pip install python-whois'"""
)
try:
import exrex
except ImportError:
sys.exit(
"""You need exrex!
install it from http://pypi.python.org/pypi/exrex
or run 'pip install exrex'"""
)
try:
from colorama import init
from colorama import Fore, Back, Style
except ImportError:
sys.exit(
"""You need colorama!
install it from http://pypi.python.org/pypi/colorama
or run 'pip install colorama'"""
)
# Init colorama
init(autoreset=True)
# Check Python Version
if sys.version_info < (3, 6):
print('Error. Python version 3.6 or later required to run this script')
print('Your version:', sys.version)
sys.exit(-1)
# Global constants
__version__: str = '0.2.26.1'
FR: str = Fore.RESET
FW: str = Fore.WHITE
FG: str = Fore.GREEN
FRC: str = Fore.RED
FC: str = Fore.CYAN
FY: str = Fore.YELLOW
FM: str = Fore.MAGENTA
FB: str = Fore.BLUE
FBC: str = Fore.BLACK
FLW: str = Fore.LIGHTWHITE_EX
FLG: str = Fore.LIGHTGREEN_EX
FLR: str = Fore.LIGHTRED_EX
FLC: str = Fore.LIGHTCYAN_EX
FLY: str = Fore.LIGHTYELLOW_EX
FLM: str = Fore.LIGHTMAGENTA_EX
FLB: str = Fore.LIGHTBLUE_EX
FLBC: str = Fore.LIGHTBLACK_EX
BLB: str = Back.LIGHTBLACK_EX
BLR: str = Back.LIGHTRED_EX
BLC: str = Back.LIGHTCYAN_EX
BC: str = Back.CYAN
BLY: str = Back.LIGHTYELLOW_EX
BY: str = Back.YELLOW
BLW: str = Back.LIGHTWHITE_EX
BW: str = Back.WHITE
BR: str = Back.RESET
SDIM: str = Style.DIM
SNORMAL: str = Style.NORMAL
SBRIGHT: str = Style.BRIGHT
SR: str = Style.RESET_ALL
SEP: str = os.sep
pathname: str = os.path.dirname(os.path.abspath(__file__))
# Folder for storing the whois cache.
WHOIS_CACHE_PATH: str = pathname + SEP + 'ddec-cache' + SEP
# SMTP options
SMTP_SERVER: str = os.getenv('SMTP_SERVER', 'localhost')
SMTP_PORT: int = int(os.getenv('SMTP_PORT', '25'))
# SMTP_SERVER: str = os.getenv('SMTP_SERVER', 'smtp.gmail.com')
# SMTP_PORT: int = int(os.getenv('SMTP_PORT', '587')) # For starttls
# SMTP_SERVER: str = os.getenv('SMTP_SERVER', 'smtp.mail.ru')
# SMTP_PORT: int = int(os.getenv('SMTP_PORT', '25')) # Default
# SMTP_SERVER: str = os.getenv('SMTP_SERVER', 'smtp.yandex.ru')
# SMTP_PORT: int = int(os.getenv('SMTP_PORT', '465')) # For SSL
SMTP_SENDER: str = os.getenv('SMTP_SENDER', 'root')
SMTP_PASSWORD: str = os.getenv('SMTP_PASSWORD', 'P@ssw0rd')
# Telegram bot options
# Proxy for telegram
TELEGRAM_PROXIES: Dict = {}
# TELEGRAM_PROXIES: Dict = {
# 'http': 'socks5://127.0.0.1:9150',
# 'https': 'socks5://127.0.0.1:9150',
# }
# Get help from https://core.telegram.org/bots
# token that can be generated talking with @BotFather on telegram
TELEGRAM_TOKEN: str = '<INSERT YOUR TOKEN>'
# channel id for telegram
TELEGRAM_CHAT_ID: str = '<INSERT YOUR CHANNEL ID>'
# url for post request to api.telegram.org
TELEGRAM_URL: str = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}/'
if str(os.getenv('SMTP_CHECK_SSL_HOSTNAME')) == '0':
SMTP_CHECK_SSL_HOSTNAME: bool = False
else:
SMTP_CHECK_SSL_HOSTNAME: bool = True
REQUEST_HEADERS: Dict = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/124.0.0.0 Safari/537.36'
}
# Options for an external utility whois
# Keywords for whois-data
EXPIRE_STRINGS: Tuple = (
'registry expiry date:',
'expiration:',
'domain expiration date:',
'registrar registration expiration date:',
'expire:',
'expires:',
'paid-till:',
'option expiration date:',
'[expires on]',
'expiry date:',
'expiration date:',
'expiration time:',
'renewal date:',
'paid-till:',
'domain expires:',
'expires on:',
'expires on:',
'valid until:',
'registry expiry date:',
'[有効期限]',
)
REGISTRAR_STRINGS: Tuple = (
'[registrant]',
'registrar:',
'registrant:',
# 'status:',
'sponsoring registrar:',
)
WHOIS_SERVER_STRINGS: Tuple = (
'registrar whois server:',
'whois server:',
)
NOT_FOUND_STRINGS: Tuple = (
'not found',
'no match for domain',
'not currently eligible for renewal',
'no entries found for the selected source(s).',
)
# Unsupported domains (all lowercase !!!)
# this tuple contains fragments of word endings
UNSUPPORTED_DOMAINS: Tuple = (
'.gov',
'denic.de',
'.eu',
'.au',
)
# Command for external whois
if sys.platform == 'win32':
WHOIS_COMMAND: str = f'{pathname}{SEP}winbin{SEP}whois-cygwin64{SEP}whois.exe'
# WHOIS_COMMAND: str = f'{pathname}{SEP}winbin{SEP}whois-sysinternals{SEP}whois64.exe'
# WHOIS_COMMAND: str = f'{pathname}{SEP}winbin{SEP}whois-nir-sofer{SEP}WhoisCL.exe'
else:
WHOIS_COMMAND: str = 'whois'
# Timeout for external whois
WHOIS_COMMAND_TIMEOUT: int = 20
# The list of expired domains
EXPIRES_DOMAIN: Dict = {}
# The list of soon domains
SOON_DOMAIN: Dict = {}
# List of domains for which the WHOIS text has changed
WHOIS_TEXT_CHANGED_DOMAIN: Dict = {}
# The list of error domains
ERRORS_DOMAIN: Dict = {} # Common errors
ERRORS2_DOMAIN: Dict = {} # limit connection
FREE_DOMAINS: Dict = {} # Free domains
# Command line parameters
CLI: Optional[Any] = None
# The number of days that are added to the expiration
# date of the domain registration
# in order to mark the expiration of the domain that
# is coming soon
G_SOON_ADD: int = 21
# List of domains processed from file
G_DOMAINS_LIST: List = []
# Currency symbol
# G_CURRENCY_SYMBOL: str = '₽'
G_CURRENCY_SYMBOL: str = '¥'
# G_CURRENCY_SYMBOL: str = '£'
# G_CURRENCY_SYMBOL: str = '€'
# G_CURRENCY_SYMBOL: str = '$'
# Counters:
# Total Domains
G_DOMAINS_TOTAL: int = 0
# Valid Domains
G_DOMAINS_VALID: int = 0
# Soon Domains
G_DOMAINS_SOON: int = 0
# The total price for the domains of this group
G_TOTAL_COST_SOON: int = 0
# Expired Domains
G_DOMAINS_EXPIRE: int = 0
# Free Domains
G_DOMAINS_FREE: int = 0
# The total price for the domains of this group
G_TOTAL_COST_EXPIRE: int = 0
# Error Domains
G_DOMAINS_ERROR: int = 0
def remove_control_characters_of_colorama(text: str) -> str:
"""
Remove all colorama control characters from a string
:param text: str
:return: str
"""
words: Tuple = (
FR,
FW,
FG,
FRC,
FC,
FY,
FM,
FB,
FBC,
FLW,
FLG,
FLR,
FLC,
FLY,
FLM,
FLB,
FLBC,
BLB,
BLR,
BLC,
BC,
BLY,
BLW,
BW,
BR,
SDIM,
SNORMAL,
SBRIGHT,
SR,
)
for word in words:
text = text.replace(word, '')
return text
def save_whois_cache(file: str, json_data: Dict) -> None:
"""
Save of the json whois data to json cache file
:param file: str
:param json_data: Dict
:return: None
"""
save_file: str = f'{WHOIS_CACHE_PATH}{file}'
with io.open(save_file, 'w+', encoding='utf8', newline='\n') as f:
json.dump(json_data, f, indent=4, ensure_ascii=False)
def load_whois_cache(file: str) -> Optional[Dict]:
"""
Load of the json whois data from json cache file
:param file: str
:return: json Dict or None
"""
json_data: Optional[Dict] = None
saved_file: str = f'{WHOIS_CACHE_PATH}{file}'
if os.path.exists(saved_file):
with open(saved_file, 'r+', encoding='utf8') as f:
try:
json_data = json.load(f)
except Exception as e:
print(
f'{FLR}Error load file: {FLW}{saved_file}\n'
f'{FLR}{str(e)}'
)
return json_data
def compare_whois_text(f1: str, f2: str, domain: str = None) -> str:
"""
Compare two whois text
:param f1: str
:param f2: str
:param domain: str
:return: str
"""
f1_list: List = f1.splitlines(keepends=True)
f2_list: List = f2.splitlines(keepends=True)
f1_list_fixed: List = []
f2_list_fixed: List = []
for line1 in f1_list:
f1_list_fixed.append(f'{line1.lower().strip()}\n')
for line2 in f2_list:
f2_list_fixed.append(f'{line2.lower().strip()}\n')
diff: Optional[Any] = difflib.ndiff(f1_list_fixed, f2_list_fixed)
# TODO: For future functionality
# diff_html = difflib.HtmlDiff(tabsize=2)
# with open(f'{domain}.html', 'w', encoding='utf-8') as fp:
# html = diff_html.make_file(
# fromlines=f1_list_fixed,
# tolines=f2_list_fixed,
# fromdesc='Original',
# todesc='Modified',
# )
# fp.write(html)
delta: str = ''
is_found: bool = False
for x in diff:
line_diff: str = x.lower().strip()
if (
'updated date:' in line_diff or
'% timestamp:' in line_diff or
'whois lookup made at ' in line_diff or
'last update of whois ' in line_diff or
'last updated on' in line_diff
):
continue
elif line_diff.startswith('- '):
is_found = not is_found
delta += f'{FRC}{x}'
elif line_diff.startswith('+ '):
is_found = not is_found
delta += f'{FG}{x}'
elif line_diff.startswith('? ') and is_found:
is_found = False
delta += f'{FC}{x}'
# else:
# delta += f'{FLC}{x}'
if delta != '':
delta += f'{FR}'
return delta
def whois_check() -> None:
"""
External whois availability check
:return: None
"""
global WHOIS_COMMAND
str_tmp: str = ""
whois_found: bool = False
if sys.platform == 'win32':
delemiter: str = ';'
s_path: str = 'Path'
else:
delemiter: str = ':'
s_path: str = 'PATH'
os_env_path = os.environ.get(s_path).split(delemiter)
for item in os_env_path:
str_tmp = item
if str_tmp != '':
if str_tmp[-1] != SEP:
str_tmp += SEP
str_tmp += 'whois'
if sys.platform == 'win32':
str_tmp += '.exe'
if Path(str_tmp).is_file():
whois_found = True
break
if whois_found:
WHOIS_COMMAND = str_tmp
if not CLI.no_banner:
print(
f'\tThe {FLG}whois{FR} found in: {FC}{str_tmp}'
)
else:
print(f'\tThe {FLR}whois{FR} not found!')
if sys.platform == 'win32':
print(
'\tPlease, install the cygwin from '
'https://www.cygwin.com/ to c:\\cygwin64 (as sample)\n'
'\tChoice in installer whois and install it.\n'
'\tAfter it, add path to c:\\cygwin64\\bin to system PATH variable.\n'
)
elif sys.platform == 'linux':
print(
'\tPlease, install the whois\n\n'
'\t\tFor Ubuntu/Debian:\n'
'\t\t\tsudo apt update && sudo apt upgrade\n'
'\t\t\tsudo apt install whois\n\n'
'\t\tFor older RHEL/CentOS/Fedora\n'
'\t\t\tand other older RPM-Based Linux:\n'
'\t\t\tFor RHEL 6.x/CentOS 6.x:\n'
'\t\t\t\tsudo yum install jwhois\n\n'
'\t\t\tFor RHEL 7.x/CentOS 7.x/Fedora 22/Rocky Linux/Alma Linux\n'
'\t\t\tand other RPM-Based Linux:\n'
'\t\t\t\tsudo dnf install jwhois\n\n'
'\t\tFor Arch/Manjaro:\n'
'\t\t\tsudo pacman -S whois\n'
)
elif sys.platform == 'darwin':
print(
'\tPlease, install the whois\n'
'\t\tbrew install whois\n'
'\t\t(Homebrew: https://brew.sh)'
)
if not whois_found:
sys.exit(-1)
def make_whois_query(domain: str, domain_group: str) -> Tuple:
"""
Execute a external whois and parse the data to extract specific data
:param domain: str
:param domain_group: str
:return: Tuple
"""
global ERRORS_DOMAIN
global G_DOMAINS_ERROR
try:
p = subprocess.Popen([WHOIS_COMMAND, domain],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except Exception as e:
print(
f'{FLR}Unable to Popen() the whois binary.\n'
f'Domain: {domain}.\n'
f'Exception: {e}')
sys.exit(-1)
try:
whois_data = p.communicate(timeout=WHOIS_COMMAND_TIMEOUT)[0]
except Exception as e:
whois_data = str(e)
tmp_list = []
if ERRORS_DOMAIN.get(domain_group) is not None:
tmp_list = ERRORS_DOMAIN[domain_group]
if domain.lower() not in tmp_list:
G_DOMAINS_ERROR += 1
tmp_list.append(domain.lower())
ERRORS_DOMAIN[domain_group] = tmp_list
else:
G_DOMAINS_ERROR += 1
tmp_list.append(domain.lower())
ERRORS_DOMAIN[domain_group] = tmp_list
if 'timed out after' in whois_data.lower():
return whois_data, None, None, None, 25
elif 'failed to retrieve the whois record' in whois_data.lower():
return whois_data, None, None, None, 26
else:
return None, None, None, None, 1
# TODO: For future functionality
# Work around whois issue #55 which returns a non-zero
# exit code for valid domains.
# if p.returncode != 0:
# print('The WHOIS utility exit()'ed with a non-zero return code')
# sys.exit(-1)
whois_data = str(whois_data, 'utf-8', 'ignore')
(
r_w_data,
r_expir_date,
r_reg,
r_w_server,
r_error
) = parse_whois_data(domain=domain, domain_group=domain_group, whois_data=whois_data)
if r_w_data is not None:
whois_data = r_w_data
return whois_data, r_expir_date, r_reg, r_w_server, r_error
def parse_whois_data(domain: str, domain_group: str, whois_data: str) -> Tuple:
"""
Grab the registrar and expiration date from the WHOIS data
:param domain: str
:param domain_group: str
:param whois_data: str
:return: Tuple
"""
global ERRORS2_DOMAIN
raw_whois_data = None
expiration_date = None
registrar = None
whois_server = None
ret_error = None
tmp_whois_data = whois_data.lower()
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
# Init colorama again
init(autoreset=True)
if 'connection timed out' in tmp_whois_data:
# Connection timed out
ret_error = 25
return raw_whois_data, None, None, None, ret_error
elif 'failed to retrieve the whois record' in tmp_whois_data:
# Failed to retrieve the WHOIS record of the specified domain
ret_error = 26
return raw_whois_data, None, None, None, ret_error
elif (
'no entries found for the selected source(s)' in tmp_whois_data
) or (
'domain not found.' in tmp_whois_data
) or (
'status: free' in tmp_whois_data
) or (
f'no match for domain "{domain}"' in tmp_whois_data
):
# It is Free!
# print(f'{FC}{tmp_whois_data}')
ret_error = 11
return raw_whois_data, None, None, None, ret_error
elif 'http://www.denic.de/en/domains/whois-service/web-whois.html' in tmp_whois_data:
# denic.de
ret_error = 22
return raw_whois_data, None, None, None, ret_error
elif 'https://www.dnc.org.nz/whois/search?domain_name=' in tmp_whois_data:
# *.nz
ret_error = 23
return raw_whois_data, None, None, None, ret_error
elif 'https://dnc.org.nz/enquiry-form/' in tmp_whois_data:
# *.nz new version of this site
ret_error = 231
return raw_whois_data, None, None, None, ret_error
elif 'the registration of this domain is restricted' in tmp_whois_data:
# TODO: idiotic service where designated links don't exist
# the registration of this domain is restricted,
# as it is protected by the identity digital dpml brand protection policy.
# additional information can be found at
# https://www.identity.digital/what-we-do/brand-protection.
ret_error = 24
return raw_whois_data, None, None, None, ret_error
elif 'https://whois.dot.ph/' in tmp_whois_data:
# whois.dot.ph
try:
page = requests.get(
f'https://whois.dot.ph/?utf8=%E2%9C%93&search={domain}',
timeout=10,
headers=REQUEST_HEADERS,
verify=True,
)
except requests.exceptions.RequestException:
ret_error = -1
print(f'{FLR}Failed to fetch remote blocklist providers. Continue...')
return raw_whois_data, None, None, None, ret_error
html = page.content.decode('utf-8', 'ignore').lower()
raw_whois_data = html
if 'domain is available.' in html:
ret_error = 11
return raw_whois_data, None, None, None, ret_error
elif 'var expirydate = moment(' in html:
for line in html.splitlines():
if 'var expirydate = moment(' in line:
if 'registrar:' in line:
registrar = line.replace(
'registrar:', ''
).replace(
'<br>', ''
)
str_date = line.replace(
"var expirydate = moment('", ''
).replace(
"').format('yyyy-mm-ddthh:mm:ss z');", ''
)
expiration_date = dateutil.parser.parse(
str_date, ignoretz=True)
break
elif 'www.dominios.es' in tmp_whois_data:
# whois.nic.es
try:
page = requests.get(
f'https://www.iana.org/whois?q={domain}',
timeout=10,
headers=REQUEST_HEADERS,
verify=True,
)
except requests.exceptions.RequestException:
ret_error = -1
print(f'{FLR}Failed to fetch remote blocklist providers. Continue...')
return raw_whois_data, None, None, None, ret_error
html = page.content.decode('utf-8', 'ignore').lower()
raw_whois_data = html
if 'status: active' in html:
ret_error = 232
for line in html.splitlines():
if 'changed: ' in line:
str_date = line.replace(
'changed:', ''
).strip()
expiration_date = dateutil.parser.parse(
str_date, ignoretz=True)
elif 'whois: ' in line:
whois_server = line.replace(
'whois:', ''
).strip()
elif 'organisation: ' in line:
registrar = line.replace(
'organisation:', ''
).strip()
return raw_whois_data, expiration_date, registrar, whois_server, ret_error
else:
raw_whois_data = tmp_whois_data
for line in tmp_whois_data.splitlines():
if line.strip() == '':
continue
if 'your connection limit exceeded. please slow down and try again later.' in line:
# Interval is small
ret_error = 2
tmp_list = []
if ERRORS2_DOMAIN.get(domain_group) is not None:
tmp_list = ERRORS2_DOMAIN[domain_group]
if domain.lower() not in tmp_list:
tmp_list.append(domain.lower())
ERRORS2_DOMAIN[domain_group] = tmp_list
else:
tmp_list.append(domain.lower())
ERRORS2_DOMAIN[domain_group] = tmp_list
return raw_whois_data, None, None, None, ret_error
if any(not_found_string in line for not_found_string in NOT_FOUND_STRINGS):
# Is it Free?
return raw_whois_data, None, None, None, ret_error
if any(expire_string in line for expire_string in EXPIRE_STRINGS):
if not expiration_date:
try:
str_date = line.partition(': ')[2]
if str_date == '':
str_date = line.partition(']')[2]
str_date = str_date.replace('/', '-')
expiration_date = dateutil.parser.parse(
str_date, ignoretz=True)
except Exception:
ret_error = 1
if any(registrar_string in line for registrar_string in REGISTRAR_STRINGS):
if not registrar:
registrar = line.partition(': ')[2].strip()
if any(whois_server_string in line for whois_server_string in
WHOIS_SERVER_STRINGS):
if not whois_server:
whois_server = line.partition(': ')[2].strip()
return raw_whois_data, expiration_date, registrar, whois_server, ret_error
def calculate_expiration_days(expiration_date: datetime) -> int:
"""
Check to see when a domain will expire
:param expiration_date: datetime
:return: int
"""
try:
domain_expire = expiration_date - datetime.now()
except Exception as e:
print(f'{FLR}Unable to calculate the expiration days.\nError: {str(e)}')
sys.exit(-1)
return domain_expire.days
def make_report_for_telegram() -> None:
"""
Make report for send through the Telegram bot.
:return: None
"""
g_total_cost: int = G_TOTAL_COST_SOON + G_TOTAL_COST_EXPIRE
if (
len(EXPIRES_DOMAIN) == 0 and
len(SOON_DOMAIN) == 0 and
len(ERRORS_DOMAIN) == 0 and
len(ERRORS2_DOMAIN) == 0 and
len(FREE_DOMAINS) == 0 and
len(WHOIS_TEXT_CHANGED_DOMAIN) == 0
):
return None
today: str = f'{datetime.now():%d.%m.%Y %H:%M}'
hl: str = f'{"-" * 42}'
message: str = ''
message += f'<b>Domains Report [ {today} ]</b>\n'
if len(EXPIRES_DOMAIN) > 0:
# add expiring domains
message += '\n<b>Domains are expiring</b><pre>'
message += f'\n{hl} DL\n'
group_i: int = 0
i: int = 0
for group, list_of_dict_data in EXPIRES_DOMAIN.items():
group_i += 1
s_g_cr: str = '\n' if group_i > 1 else ''
if group != '/':
str_domain_item: str = f'\n{s_g_cr}{group_i:>4}. {group}\n\n'
message += str_domain_item
for item_dict_data in list_of_dict_data:
for domain, day_left in item_dict_data.items():
i += 1
dn: str = f'{domain:<37}'
str_domain_item: str = f'{i:>5}. {dn} {day_left}\n'
message += str_domain_item
message += '</pre>'
if len(SOON_DOMAIN) > 0:
# add soon domains
message += '\n\n<b>Domains are expiring soon</b><pre>'
message += f'\n{hl} DL\n'
group_i: int = 0
i: int = 0
for group, list_of_dict_data in SOON_DOMAIN.items():
group_i += 1
s_g_cr: str = '\n' if group_i > 1 else ''
if group != '/':
str_domain_item: str = f'\n{s_g_cr}{group_i:>4}. {group}\n\n'
message += str_domain_item
for item_dict_data in list_of_dict_data:
for domain, day_left in item_dict_data.items():
i += 1
dn: str = f'{domain:<37}'
str_domain_item: str = f'{i:>5}. {dn} {day_left}\n'
message += str_domain_item
message += '</pre>'
if len(ERRORS_DOMAIN) > 0:
# add error domains
message += '\n\n<b>Domains that caused errors</b><pre>'
message += f'\n{hl}\n'
group_i: int = 0
i: int = 0
for group, list_of_domains in ERRORS_DOMAIN.items():
group_i += 1
s_g_cr: str = '\n' if group_i > 1 else ''
if group != '/':
str_domain_item: str = f'\n{s_g_cr}{group_i:>4}. {group}\n\n'
message += str_domain_item
for domain in list_of_domains:
i += 1
dn: str = f'{domain:<37}'
str_domain_item: str = f'{i:>5}. {dn}\n'
message += str_domain_item
message += '</pre>'
if len(ERRORS2_DOMAIN) > 0:
# add error2 domains
message += '\n\n<b>Exceeded the limit on whois</b><pre>'
message += f'\n{hl}\n'
group_i: int = 0
i: int = 0
for group, list_of_domains in ERRORS2_DOMAIN.items():
group_i += 1
s_g_cr: str = '\n' if group_i > 1 else ''
if group != '/':
str_domain_item: str = f'\n{s_g_cr}{group_i:>4}. {group}\n\n'
message += str_domain_item
for domain in list_of_domains:
i += 1
dn: str = f'{domain:<37}'
str_domain_item: str = f'{i:>5}. {dn}\n'
message += str_domain_item
message += '</pre>'
if len(FREE_DOMAINS) > 0:
# add free domains
message += '\n\n<b>Free domains</b><pre>'
message += f'\n{hl}\n'
group_i: int = 0
i: int = 0
for group, list_of_domains in FREE_DOMAINS.items():
group_i += 1
s_g_cr: str = '\n' if group_i > 1 else ''
if group != '/':
str_domain_item: str = f'\n{s_g_cr}{group_i:>4}. {group}\n\n'
message += str_domain_item
for domain in list_of_domains:
i += 1
dn: str = f'{domain:<37}'
str_domain_item: str = f'{i:>5}. {dn}\n'
message += str_domain_item
message += '</pre>'
if len(WHOIS_TEXT_CHANGED_DOMAIN) > 0:
# add whois-text changed domains
message += '\n\n<b>Domains whose whois text has changed</b><pre>'
message += f'\n{hl}\n'
group_i: int = 0
i: int = 0
for group, list_of_dict_data in WHOIS_TEXT_CHANGED_DOMAIN.items():
group_i += 1
s_g_cr: str = '\n' if group_i > 1 else ''
if group != '/':
str_domain_item: str = f'\n{s_g_cr}{group_i:>4}. {group}\n\n'
message += str_domain_item
for item_dict_data in list_of_dict_data:
for domain, value in item_dict_data.items():
i += 1
dn: str = f'{domain:<20}'
txt: str = value.get('txt')
if CLI.trim_long_whois_text:
if len(txt) > 350:
dt: str = value.get('dt')
str_domain_item: str = (
f'{i:>5}. {dn}{dt}\n\n'
f'{txt[:350]}...\n\n'
)
else:
dt: str = value.get('dt')
str_domain_item: str = (
f'{i:>5}. {dn}{dt}\n\n'
f'{txt}\n\n'
)
else:
dt: str = value.get('dt')
str_domain_item: str = (
f'{i:>5}. {dn}{dt}\n\n'
f'{txt}\n\n'
)
message += str_domain_item
message += '</pre>'
if g_total_cost > 0:
message += '\n\n<b>Cost</b><pre>'
message += f'\n{hl}\n'
if G_TOTAL_COST_EXPIRE > 0:
message += (
f'For Expires : '
f'{G_CURRENCY_SYMBOL} '
f'{round(G_TOTAL_COST_EXPIRE, 2)}\n'
)
if G_TOTAL_COST_SOON > 0:
message += (
f'For Soon : '
f'{G_CURRENCY_SYMBOL} '
f'{round(G_TOTAL_COST_SOON, 2)}\n'
)
message += f'{hl}\n'
message += (
f'Total : '
f'{G_CURRENCY_SYMBOL} '
f'{round(g_total_cost, 2)}\n'
)
message += '</pre>'
if len(message) <= 3800: # 4086
send_telegram(message)
else:
if not CLI.split_long_message:
message = message[:3700]
if not message.endswith('</pre>'):
message += '</pre>'
tmp_txt = ''
if not CLI.trim_long_whois_text:
tmp_txt = (
'<b>-trim</b>'
' and/or '
)
message += (
f'\n...\n'