11import datetime
2+ import logging
23import json
34
45from urllib .request import ssl , socket
56
67
8+ logger = logging .getLogger (__name__ )
9+
10+
711def check_ssl (hostname : str , port : str ) -> dict :
812 """
913 This function is check ssl certificate
@@ -13,17 +17,27 @@ def check_ssl(hostname: str, port: str) -> dict:
1317 """
1418 context = ssl .create_default_context ()
1519
16- with socket .create_connection ((hostname , port )) as sock :
17- with context .wrap_socket (sock , server_hostname = hostname ) as ssock :
18- certificate = ssock .getpeercert ()
19-
20- certExpires = datetime .datetime .strptime (
21- certificate ['notAfter' ], '%b %d %H:%M:%S %Y %Z' )
22-
23- return {
24- 'Expiration Day' : f"{ certExpires .year } -{ certExpires .month } -{ certExpires .day } " ,
25- 'Remaining Day' : (certExpires - datetime .datetime .now ()).days
26- }
20+ try :
21+ with socket .create_connection (address = (hostname , port ), timeout = 3 ) as sock :
22+ with context .wrap_socket (sock , server_hostname = hostname ) as ssock :
23+ certificate = ssock .getpeercert ()
24+
25+ certExpires = datetime .datetime .strptime (
26+ certificate ['notAfter' ], '%b %d %H:%M:%S %Y %Z' )
27+
28+ data = {
29+ 'status' : 200 ,
30+ 'expiration_day' : f"{ certExpires .year } -{ certExpires .month } -{ certExpires .day } " ,
31+ 'remaining_day' : (certExpires - datetime .datetime .now ()).days
32+ }
33+ except Exception as e :
34+ logger .error (e )
35+ data = {
36+ 'status' : 500 ,
37+ 'message' : 'Server Error! Try again or contact admin.'
38+ }
39+
40+ return data
2741
2842
2943def run (event , context ) -> list :
0 commit comments