2021-03-26

**Python SSL Certificate Checker **

Continuing our Networking Automation using Python blog series, here is the Part 7.

In this part we are explaining python script which will check the expiry date of a SSL certificate from a list of IP address and send an e-mail automatically if the certificate expiry date is nearing. The IP addresses can be of your load balancer VIP or Server IP address or any device IP address. You can use same script to check SSL certificate for any port number like 443,587,993,995,465 etc.

Basic Requirements

  1. Python 3.6
  2. server_ip.txt , a text file which contains all device IP address
  3. A email account on www.outlook.com . You can use any other mail account by editing SMTP server detail on the script. Please let us know if you want customised script which will sent mail from your corporate mail account or Microsoft Outlook.

Please read part 1 and part 2 to get started with python and how to run your first program.

This script have two files

  1. server_ip.txt -> this file store all the device IP address
  2. sslcheck.py -> This is the python script

——————- advertisements ——————-

———————————————————-

How to run :

Step 1. Download the sslcheck and server_ip to the same folder

Step 2. Change the sslcheck.txt to sslcheck.py

Step 3. Open server_ip.txt and save with all your device IP address with port number whose SSL certificate need to be check.

Step 4. Open command prompt “CMD” and navigate to the folder where you have saved script and ‘server_ip.txt’

Step 5. Run script by typing “python sslcheck.py” on command prompt

Step 6.It will ask for threshold date, from mail id , to mail id and credentials. Please provide the same

Step 7. Script will go though each device SSL certificate and sent mail if anything going to expire within given number of days.

Script Details

import ssl
from datetime import datetime
import pytz
import OpenSSL
import socket
import getpass
from datetime import timedelta
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

print(“Program to check SSL certificate validity \n”)

opening file

ipfile=open(‘server_ip.txt’)
cur_date = datetime.utcnow()
mailbody=””
expcount=0

getting details

expday=input(“Please provide threshold expiry date :”)
from_mail=input(“Your mail id : “)
passwd=getpass.getpass(“password : “)
to_mail=input(“Target mail id : “)

checking certificate validity. for loop to go through each IP in server_ip.txt file

for ip in ipfile:
try:
host = ip.strip().split(“:”)[0]
port = ip.strip().split(“:”)[1]
print(“\nChecking certifcate for server “,host)
ctx = OpenSSL.SSL.Context(ssl.PROTOCOL_TLSv1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
cnx = OpenSSL.SSL.Connection(ctx, s)
cnx.set_connect_state()
cnx.do_handshake()
cert=cnx.get_peer_certificate()
s.close()
server_name = cert.get_subject().commonName
print (server_name)

checking expiry date

edate=cert.get_notAfter()
edate=edate.decode()

converting in to system time format

exp_date = datetime.strptime(edate,’%Y%m%d%H%M%SZ’)
days_to_expire = int((exp_date – cur_date).days)
print(“day to expire”,days_to_expire)

preparing mail body

if days_to_expire < int(expday) :
expcount=expcount+1
mailbody=mailbody+”\n Server name =”+server_name+”, Days to expire:”+str(days_to_expire)

except:
print (“error on connection to Server,”,host)
print (mailbody)

sending mail if any certificate going to expire within threshold days

if expcount >= 1 :
try:
print(“\nCertifcate alert for “+str(expcount)+” Servers,Sending mails”)

body=”Following certificate going to expire, please take action \n”+mailbody
s = smtplib.SMTP(host=’smtp-mail.outlook.com’, port=587) # change here if you want to use other smtp server
s.starttls()
s.login(from_mail,passwd)

msg = MIMEMultipart() # create a message
msg[‘From’]=from_mail
msg[‘To’]=to_mail
msg[‘Subject’]=”Certificate Expire alert”

add in the message body

msg.attach(MIMEText(str(body),’plain’))

send the message via the server set up earlier.

s.send_message(msg)
print(“Mail sent”)
s.close()
except:
print (“Sending mail failed”)
else :
print(“All certificate are below the threshold date”)

print (‘\nCert check completed’)

**Sample Output **

Below images are sample script and a sample e-mail alert.

image
image

Sample e-mail alert

Hope this post helped you. You can read more posts on Network automation using Python here. Please use the comments section for any queries/suggestions .

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末牲平,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌礼华,老刑警劉巖翩伪,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件春塌,死亡現(xiàn)場(chǎng)離奇詭異凳忙,居然都是意外死亡疫赎,警方通過查閱死者的電腦和手機(jī)宫补,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門檬姥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人粉怕,你說我怎么就攤上這事健民。” “怎么了贫贝?”我有些...
    開封第一講書人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵荞雏,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng)凤优,這世上最難降的妖魔是什么悦陋? 我笑而不...
    開封第一講書人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮筑辨,結(jié)果婚禮上俺驶,老公的妹妹穿的比我還像新娘。我一直安慰自己棍辕,他們只是感情好暮现,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著楚昭,像睡著了一般栖袋。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上抚太,一...
    開封第一講書人閱讀 52,262評(píng)論 1 308
  • 那天塘幅,我揣著相機(jī)與錄音,去河邊找鬼尿贫。 笑死电媳,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的庆亡。 我是一名探鬼主播匾乓,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼又谋!你這毒婦竟也來了拼缝?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤彰亥,失蹤者是張志新(化名)和其女友劉穎咧七,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體剩愧,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡猪叙,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了仁卷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片穴翩。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖锦积,靈堂內(nèi)的尸體忽然破棺而出芒帕,到底是詐尸還是另有隱情,我是刑警寧澤丰介,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布背蟆,位于F島的核電站鉴分,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏带膀。R本人自食惡果不足惜志珍,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望垛叨。 院中可真熱鬧伦糯,春花似錦、人聲如沸嗽元。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽剂癌。三九已至淤翔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間佩谷,已是汗流浹背旁壮。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留琳要,地道東北人寡具。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓秤茅,卻偏偏與公主長(zhǎng)得像稚补,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子框喳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容