Check TLS/SSL
10-25-2020
Language or Platform: Python
Code:
import OpenSSL
import smtplib
import ssl
from socket import * # for timeout
import os
# sudo apt install python3-openssl
send_address = "name@email.com"
receive_address = "name@email.com"
smtp_server = "10.1.150.4"
port = 25
ssl_log = "ssl.log"
def send_mail():
report_file = open(ssl_log)
group_text = report_file.read()
message = "Subject: Certificate Expiration - Python Script\n\n" + group_text
try:
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo()
#server.starttls()
server.sendmail(send_address, receive_address, message)
server.quit()
except:
print("\nSMTP: NO CONNECTION\n")
def check_cert(servername, serverport):
# get SSL Cert info
setdefaulttimeout(10)
try:
cert = ssl.get_server_certificate((servername, serverport))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
x509info = x509.get_notAfter()
exp_month = x509info[4:6].decode('utf-8')
exp_day = x509info[6:8].decode('utf-8')
exp_year = x509info[:4].decode('utf-8')
exp_date = str(exp_month) + "-" + str(exp_day) + "-" + str(exp_year)
print(servername.ljust(35), " - SSL Certificate expires on ", exp_date)
logline = (servername.ljust(25) + " - SSL Certificate expires on " + exp_date)
with open(ssl_log,'a') as log:
log.write(logline + "\n")
except (error, timeout) as err:
print("No connection: {0}".format(err), " -", servername)
os.system('cls' if os.name == 'nt' else 'clear')
open(ssl_log, 'w').close()
array = []
with open("serverlist.txt", "r") as f:
# Make sure you don't have a blank line at end of serverlist.txt!
for line in f:
servername = line.split()[0]
serverport = line.split()[1]
check_cert(servername.strip(), serverport.strip())
send_mail()
Back